{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":39272,"databundleVersionId":4629629,"sourceType":"competition"},{"sourceId":1771472,"sourceType":"datasetVersion","datasetId":1053037},{"sourceId":4874049,"sourceType":"datasetVersion","datasetId":2717932},{"sourceId":4910242,"sourceType":"datasetVersion","datasetId":2117595},{"sourceId":5064496,"sourceType":"datasetVersion","datasetId":2567502},{"sourceId":104036025,"sourceType":"kernelVersion"}],"dockerImageVersionId":30302,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## Initialization","metadata":{}},{"cell_type":"code","source":"# ls /kaggle/input/rsns-2022-runs/yolox-dep/","metadata":{"execution":{"iopub.status.busy":"2025-02-23T04:08:32.766989Z","iopub.execute_input":"2025-02-23T04:08:32.767422Z","iopub.status.idle":"2025-02-23T04:08:32.773046Z","shell.execute_reply.started":"2025-02-23T04:08:32.767373Z","shell.execute_reply":"2025-02-23T04:08:32.771595Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install /kaggle/input/rsns-2022-runs/yolox-dep/thop-0.1.1.post2209072238-py3-none-any.whl\n!pip install /kaggle/input/rsns-2022-runs/yolox-dep/loguru-0.6.0-py3-none-any.whl\n!pip install /kaggle/input/pycocotools202/pycocotools-2.0.2-cp37-cp37m-linux_x86_64.whl\n# !pip install /kaggle/input/rsns-2022-runs/yolox-dep/protobuf-3.20.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl\n# !pip install /kaggle/input/rsns-2022-runs/yolox-dep/onnx-1.13.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl\n# !pip install /kaggle/input/rsns-2022-runs/yolox-dep/onnx_simplifier-0.4.10-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl\n# !pip install /kaggle/input/rsns-2022-runs/yolox-dep/psutil-5.9.4-cp36-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl\n# !pip install /kaggle/input/rsns-2022-runs/yolox-dep/tabulate-0.9.0-py3-none-any.whl","metadata":{"execution":{"iopub.status.busy":"2025-02-23T04:08:32.775221Z","iopub.execute_input":"2025-02-23T04:08:32.775725Z","iopub.status.idle":"2025-02-23T04:10:39.04207Z","shell.execute_reply.started":"2025-02-23T04:08:32.775683Z","shell.execute_reply":"2025-02-23T04:10:39.040943Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!cp -r /kaggle/input/rsns-2022-runs/YOLOX /kaggle/working\n!pip install --no-deps /kaggle/working/YOLOX","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:10:39.044394Z","iopub.execute_input":"2025-02-23T04:10:39.044718Z","iopub.status.idle":"2025-02-23T04:11:40.812933Z","shell.execute_reply.started":"2025-02-23T04:10:39.044687Z","shell.execute_reply":"2025-02-23T04:11:40.811542Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install /kaggle/input/rsna-2022-whl/{pydicom-2.3.0-py3-none-any.whl,pylibjpeg-1.4.0-py3-none-any.whl,python_gdcm-3.0.15-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl}\n!pip install /kaggle/input/segmentation-models-pytorch-030/nvidia_dali_nightly_cuda110-1.22.0.dev20221215-6781964-py3-none-manylinux2014_x86_64.whl\n!pip install /kaggle/input/rsnamodules/dicomsdl-0.109.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_kg_hide-input":true,"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:11:40.814848Z","iopub.execute_input":"2025-02-23T04:11:40.815304Z","iopub.status.idle":"2025-02-23T04:14:00.273782Z","shell.execute_reply.started":"2025-02-23T04:11:40.815258Z","shell.execute_reply":"2025-02-23T04:14:00.272179Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"%%writefile /opt/conda/lib/python3.7/site-packages/nvidia/dali/plugin/pytorch.py\n\n# Copyright (c) 2017-2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the 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\nfrom nvidia.dali.backend import TensorGPU, TensorListGPU\nfrom nvidia.dali.pipeline import Pipeline\nimport nvidia.dali.ops as ops\nfrom nvidia.dali import types\nfrom nvidia.dali.plugin.base_iterator import _DaliBaseIterator\nfrom nvidia.dali.plugin.base_iterator import LastBatchPolicy\nimport torch\nimport torch.utils.dlpack as torch_dlpack\nimport ctypes\nimport numpy as np\n\nto_torch_type = {\n    types.DALIDataType.FLOAT:   torch.float32,\n    types.DALIDataType.FLOAT64: torch.float64,\n    types.DALIDataType.FLOAT16: torch.float16,\n    types.DALIDataType.UINT8:   torch.uint8,\n    types.DALIDataType.INT8:    torch.int8,\n    types.DALIDataType.UINT16:  torch.int16,\n    types.DALIDataType.INT16:   torch.int16,\n    types.DALIDataType.INT32:   torch.int32,\n    types.DALIDataType.INT64:   torch.int64\n}\n\n\ndef feed_ndarray(dali_tensor, arr, cuda_stream=None):\n    \"\"\"\n    Copy contents of DALI tensor to PyTorch's Tensor.\n\n    Parameters\n    ----------\n    `dali_tensor` : nvidia.dali.backend.TensorCPU or nvidia.dali.backend.TensorGPU\n                    Tensor from which to copy\n    `arr` : torch.Tensor\n            Destination of the copy\n    `cuda_stream` : torch.cuda.Stream, cudaStream_t or any value that can be cast to cudaStream_t.\n                    CUDA stream to be used for the copy\n                    (if not provided, an internal user stream will be selected)\n                    In most cases, using pytorch's current stream is expected (for example,\n                    if we are copying to a tensor allocated with torch.zeros(...))\n    \"\"\"\n    dali_type = to_torch_type[dali_tensor.dtype]\n\n    assert dali_type == arr.dtype, (\"The element type of DALI Tensor/TensorList\"\n                                    \" doesn't match the element type of the target PyTorch Tensor: \"\n                                    \"{} vs {}\".format(dali_type, arr.dtype))\n    assert dali_tensor.shape() == list(arr.size()), \\\n        (\"Shapes do not match: DALI tensor has size {0}, but PyTorch Tensor has size {1}\".\n            format(dali_tensor.shape(), list(arr.size())))\n    cuda_stream = types._raw_cuda_stream(cuda_stream)\n\n    # turn raw int to a c void pointer\n    c_type_pointer = ctypes.c_void_p(arr.data_ptr())\n    if isinstance(dali_tensor, (TensorGPU, TensorListGPU)):\n        stream = None if cuda_stream is None else ctypes.c_void_p(cuda_stream)\n        dali_tensor.copy_to_external(c_type_pointer, stream, non_blocking=True)\n    else:\n        dali_tensor.copy_to_external(c_type_pointer)\n    return arr\n\n\nclass DALIGenericIterator(_DaliBaseIterator):\n    \"\"\"\n    General DALI iterator for PyTorch. It can return any number of\n    outputs from the DALI pipeline in the form of PyTorch's Tensors.\n\n    Parameters\n    ----------\n    pipelines : list of nvidia.dali.Pipeline\n                List of pipelines to use\n    output_map : list of str\n                List of strings which maps consecutive outputs\n                of DALI pipelines to user specified name.\n                Outputs will be returned from iterator as dictionary\n                of those names.\n                Each name should be distinct\n    size : int, default = -1\n                Number of samples in the shard for the wrapped pipeline (if there is more than\n                one it is a sum)\n                Providing -1 means that the iterator will work until StopIteration is raised\n                from the inside of iter_setup(). The options `last_batch_policy` and\n                `last_batch_padded` don't work in such case. It works with only one pipeline inside\n                the iterator.\n                Mutually exclusive with `reader_name` argument\n    reader_name : str, default = None\n                Name of the reader which will be queried to the shard size, number of shards and\n                all other properties necessary to count properly the number of relevant and padded\n                samples that iterator needs to deal with. It automatically sets `last_batch_policy`\n                to PARTIAL when the FILL is used, and `last_batch_padded` accordingly to match\n                the reader's configuration\n    auto_reset : string or bool, optional, default = False\n                Whether the iterator resets itself for the next epoch or it requires reset() to be\n                called explicitly.\n\n                It can be one of the following values:\n\n                * ``\"no\"``, ``False`` or ``None`` - at the end of epoch StopIteration is raised\n                  and reset() needs to be called\n                * ``\"yes\"`` or ``\"True\"``- at the end of epoch StopIteration is raised but reset()\n                  is called internally automatically\n\n    dynamic_shape : any, optional,\n                Parameter used only for backward compatibility.\n    fill_last_batch : bool, optional, default = None\n                **Deprecated** Please use ``last_batch_policy`` instead\n\n                Whether to fill the last batch with data up to 'self.batch_size'.\n                The iterator would return the first integer multiple\n                of self._num_gpus * self.batch_size entries which exceeds 'size'.\n                Setting this flag to False will cause the iterator to return\n                exactly 'size' entries.\n    last_batch_policy: optional, default = LastBatchPolicy.FILL\n                What to do with the last batch when there are not enough samples in the epoch\n                to fully fill it. See :meth:`nvidia.dali.plugin.base_iterator.LastBatchPolicy`\n    last_batch_padded : bool, optional, default = False\n                Whether the last batch provided by DALI is padded with the last sample\n                or it just wraps up. In the conjunction with ``last_batch_policy`` it tells\n                if the iterator returning last batch with data only partially filled with\n                data from the current epoch is dropping padding samples or samples from\n                the next epoch. If set to ``False`` next\n                epoch will end sooner as data from it was consumed but dropped. If set to\n                True next epoch would be the same length as the first one. For this to happen,\n                the option `pad_last_batch` in the reader needs to be set to True as well.\n                It is overwritten when `reader_name` argument is provided\n    prepare_first_batch : bool, optional, default = True\n                Whether DALI should buffer the first batch right after the creation of the iterator,\n                so one batch is already prepared when the iterator is prompted for the data\n\n    Example\n    -------\n    With the data set ``[1,2,3,4,5,6,7]`` and the batch size 2:\n\n    last_batch_policy = LastBatchPolicy.PARTIAL, last_batch_padded = True  -> last batch = ``[7]``,\n    next iteration will return ``[1, 2]``\n\n    last_batch_policy = LastBatchPolicy.PARTIAL, last_batch_padded = False -> last batch = ``[7]``,\n    next iteration will return ``[2, 3]``\n\n    last_batch_policy = LastBatchPolicy.FILL, last_batch_padded = True   -> last batch = ``[7, 7]``,\n    next iteration will return ``[1, 2]``\n\n    last_batch_policy = LastBatchPolicy.FILL, last_batch_padded = False  -> last batch = ``[7, 1]``,\n    next iteration will return ``[2, 3]``\n\n    last_batch_policy = LastBatchPolicy.DROP, last_batch_padded = True   -> last batch = ``[5, 6]``,\n    next iteration will return ``[1, 2]``\n\n    last_batch_policy = LastBatchPolicy.DROP, last_batch_padded = False  -> last batch = ``[5, 6]``,\n    next iteration will return ``[2, 3]``\n    \"\"\"\n\n    def __init__(self,\n                 pipelines,\n                 output_map,\n                 size=-1,\n                 reader_name=None,\n                 auto_reset=False,\n                 fill_last_batch=None,\n                 dynamic_shape=False,\n                 last_batch_padded=False,\n                 last_batch_policy=LastBatchPolicy.FILL,\n                 prepare_first_batch=True):\n\n        # check the assert first as _DaliBaseIterator would run the prefetch\n        assert len(set(output_map)) == len(output_map), \"output_map names should be distinct\"\n        self._output_categories = set(output_map)\n        self.output_map = output_map\n\n        _DaliBaseIterator.__init__(self,\n                                   pipelines,\n                                   size,\n                                   reader_name,\n                                   auto_reset,\n                                   fill_last_batch,\n                                   last_batch_padded,\n                                   last_batch_policy,\n                                   prepare_first_batch=prepare_first_batch)\n\n        self._first_batch = None\n        if self._prepare_first_batch:\n            try:\n                self._first_batch = DALIGenericIterator.__next__(self)\n                # call to `next` sets _ever_consumed to True but if we are just calling it from\n                # here we should set if to False again\n                self._ever_consumed = False\n            except StopIteration:\n                assert False, \"It seems that there is no data in the pipeline. This may happen \" \\\n                       \"if `last_batch_policy` is set to PARTIAL and the requested batch size is \" \\\n                       \"greater than the shard size.\"\n\n    def __next__(self):\n        self._ever_consumed = True\n        if self._first_batch is not None:\n            batch = self._first_batch\n            self._first_batch = None\n            return batch\n\n        # Gather outputs\n        outputs = self._get_outputs()\n\n        data_batches = [None for i in range(self._num_gpus)]\n        for i in range(self._num_gpus):\n            dev_id = self._pipes[i].device_id\n            # initialize dict for all output categories\n            category_outputs = dict()\n            # segregate outputs into categories\n            for j, out in enumerate(outputs[i]):\n                category_outputs[self.output_map[j]] = out\n\n            # Change DALI TensorLists into Tensors\n            category_tensors = dict()\n            category_shapes = dict()\n            for category, out in category_outputs.items():\n                category_tensors[category] = out.as_tensor()\n                category_shapes[category] = category_tensors[category].shape()\n\n            category_torch_type = dict()\n            category_device = dict()\n            torch_gpu_device = None\n            torch_cpu_device = torch.device('cpu')\n            # check category and device\n            for category in self._output_categories:\n                category_torch_type[category] = to_torch_type[category_tensors[category].dtype]\n                if type(category_tensors[category]) is TensorGPU:\n                    if not torch_gpu_device:\n                        torch_gpu_device = torch.device('cuda', dev_id)\n                    category_device[category] = torch_gpu_device\n                else:\n                    category_device[category] = torch_cpu_device\n\n            pyt_tensors = dict()\n            for category in self._output_categories:\n                pyt_tensors[category] = torch.empty(category_shapes[category],\n                                                    dtype=category_torch_type[category],\n                                                    device=category_device[category])\n\n            data_batches[i] = pyt_tensors\n\n            # Copy data from DALI Tensors to torch tensors\n            for category, tensor in category_tensors.items():\n                if isinstance(tensor, (TensorGPU, TensorListGPU)):\n                    # Using same cuda_stream used by torch.zeros to set the memory\n                    stream = torch.cuda.current_stream(device=pyt_tensors[category].device)\n                    feed_ndarray(tensor, pyt_tensors[category], cuda_stream=stream)\n                else:\n                    feed_ndarray(tensor, pyt_tensors[category])\n\n        self._schedule_runs()\n\n        self._advance_and_check_drop_last()\n\n        if self._reader_name:\n            if_drop, left = self._remove_padded()\n            if np.any(if_drop):\n                output = []\n                for batch, to_copy in zip(data_batches, left):\n                    batch = batch.copy()\n                    for category in self._output_categories:\n                        batch[category] = batch[category][0:to_copy]\n                    output.append(batch)\n                return output\n\n        else:\n            if self._last_batch_policy == LastBatchPolicy.PARTIAL and (\n                                          self._counter > self._size) and self._size > 0:\n                # First calculate how much data is required to return exactly self._size entries.\n                diff = self._num_gpus * self.batch_size - (self._counter - self._size)\n                # Figure out how many GPUs to grab from.\n                numGPUs_tograb = int(np.ceil(diff / self.batch_size))\n                # Figure out how many results to grab from the last GPU\n                # (as a fractional GPU batch may be required to bring us\n                # right up to self._size).\n                mod_diff = diff % self.batch_size\n                data_fromlastGPU = mod_diff if mod_diff else self.batch_size\n\n                # Grab the relevant data.\n                # 1) Grab everything from the relevant GPUs.\n                # 2) Grab the right data from the last GPU.\n                # 3) Append data together correctly and return.\n                output = data_batches[0:numGPUs_tograb]\n                output[-1] = output[-1].copy()\n                for category in self._output_categories:\n                    output[-1][category] = output[-1][category][0:data_fromlastGPU]\n                return output\n\n        return data_batches\n\n\nclass DALIClassificationIterator(DALIGenericIterator):\n    \"\"\"\n    DALI iterator for classification tasks for PyTorch. It returns 2 outputs\n    (data and label) in the form of PyTorch's Tensor.\n\n    Calling\n\n    .. code-block:: python\n\n       DALIClassificationIterator(pipelines, reader_name)\n\n    is equivalent to calling\n\n    .. code-block:: python\n\n       DALIGenericIterator(pipelines, [\"data\", \"label\"], reader_name)\n\n    Parameters\n    ----------\n    pipelines : list of nvidia.dali.Pipeline\n                List of pipelines to use\n    size : int, default = -1\n                Number of samples in the shard for the wrapped pipeline (if there is more than\n                one it is a sum)\n                Providing -1 means that the iterator will work until StopIteration is raised\n                from the inside of iter_setup(). The options `last_batch_policy` and\n                `last_batch_padded` don't work in such case. It works with only one pipeline inside\n                the iterator.\n                Mutually exclusive with `reader_name` argument\n    reader_name : str, default = None\n                Name of the reader which will be queried to the shard size, number of shards and\n                all other properties necessary to count properly the number of relevant and padded\n                samples that iterator needs to deal with. It automatically sets `last_batch_policy`\n                to PARTIAL when the FILL is used, and `last_batch_padded` accordingly to match\n                the reader's configuration\n    auto_reset : string or bool, optional, default = False\n                Whether the iterator resets itself for the next epoch or it requires reset() to be\n                called explicitly.\n\n                It can be one of the following values:\n\n                * ``\"no\"``, ``False`` or ``None`` - at the end of epoch StopIteration is raised\n                  and reset() needs to be called\n                * ``\"yes\"`` or ``\"True\"``- at the end of epoch StopIteration is raised but reset()\n                  is called internally automatically\n\n    dynamic_shape : any, optional,\n                Parameter used only for backward compatibility.\n    fill_last_batch : bool, optional, default = None\n                **Deprecated** Please use ``last_batch_policy`` instead\n\n                Whether to fill the last batch with data up to 'self.batch_size'.\n                The iterator would return the first integer multiple\n                of self._num_gpus * self.batch_size entries which exceeds 'size'.\n                Setting this flag to False will cause the iterator to return\n                exactly 'size' entries.\n    last_batch_policy: optional, default = LastBatchPolicy.FILL\n                What to do with the last batch when there are not enough samples in the epoch\n                to fully fill it. See :meth:`nvidia.dali.plugin.base_iterator.LastBatchPolicy`\n    last_batch_padded : bool, optional, default = False\n                Whether the last batch provided by DALI is padded with the last sample\n                or it just wraps up. In the conjunction with ``last_batch_policy`` it tells\n                if the iterator returning last batch with data only partially filled with\n                data from the current epoch is dropping padding samples or samples from\n                the next epoch. If set to ``False`` next\n                epoch will end sooner as data from it was consumed but dropped. If set to\n                True next epoch would be the same length as the first one. For this to happen,\n                the option `pad_last_batch` in the reader needs to be set to True as well.\n                It is overwritten when `reader_name` argument is provided\n    prepare_first_batch : bool, optional, default = True\n                Whether DALI should buffer the first batch right after the creation of the iterator,\n                so one batch is already prepared when the iterator is prompted for the data\n\n    Example\n    -------\n    With the data set ``[1,2,3,4,5,6,7]`` and the batch size 2:\n\n    last_batch_policy = LastBatchPolicy.PARTIAL, last_batch_padded = True  -> last batch = ``[7]``,\n    next iteration will return ``[1, 2]``\n\n    last_batch_policy = LastBatchPolicy.PARTIAL, last_batch_padded = False -> last batch = ``[7]``,\n    next iteration will return ``[2, 3]``\n\n    last_batch_policy = LastBatchPolicy.FILL, last_batch_padded = True   -> last batch = ``[7, 7]``,\n    next iteration will return ``[1, 2]``\n\n    last_batch_policy = LastBatchPolicy.FILL, last_batch_padded = False  -> last batch = ``[7, 1]``,\n    next iteration will return ``[2, 3]``\n\n    last_batch_policy = LastBatchPolicy.DROP, last_batch_padded = True   -> last batch = ``[5, 6]``,\n    next iteration will return ``[1, 2]``\n\n    last_batch_policy = LastBatchPolicy.DROP, last_batch_padded = False  -> last batch = ``[5, 6]``,\n    next iteration will return ``[2, 3]``\n    \"\"\"\n\n    def __init__(self,\n                 pipelines,\n                 size=-1,\n                 reader_name=None,\n                 auto_reset=False,\n                 fill_last_batch=None,\n                 dynamic_shape=False,\n                 last_batch_padded=False,\n                 last_batch_policy=LastBatchPolicy.FILL,\n                 prepare_first_batch=True):\n        super(DALIClassificationIterator, self).__init__(pipelines, [\"data\", \"label\"],\n                                                         size,\n                                                         reader_name=reader_name,\n                                                         auto_reset=auto_reset,\n                                                         fill_last_batch=fill_last_batch,\n                                                         dynamic_shape=dynamic_shape,\n                                                         last_batch_padded=last_batch_padded,\n                                                         last_batch_policy=last_batch_policy,\n                                                         prepare_first_batch=prepare_first_batch)\n\n\nclass TorchPythonFunction(ops.PythonFunctionBase):\n    schema_name = \"TorchPythonFunction\"\n    ops.register_cpu_op('TorchPythonFunction')\n    ops.register_gpu_op('TorchPythonFunction')\n\n    def _torch_stream_wrapper(self, function, *ins):\n        with torch.cuda.stream(self.stream):\n            out = function(*ins)\n        self.stream.synchronize()\n        return out\n\n    def torch_wrapper(self, batch_processing, function, device, *args):\n        func = function if device == 'cpu' else \\\n               lambda *ins: self._torch_stream_wrapper(function, *ins)\n        if batch_processing:\n            return ops.PythonFunction.function_wrapper_batch(func,\n                                                             self.num_outputs,\n                                                             torch.utils.dlpack.from_dlpack,\n                                                             torch.utils.dlpack.to_dlpack,\n                                                             *args)\n        else:\n            return ops.PythonFunction.function_wrapper_per_sample(func,\n                                                                  self.num_outputs,\n                                                                  torch_dlpack.from_dlpack,\n                                                                  torch_dlpack.to_dlpack,\n                                                                  *args)\n\n    def __call__(self, *inputs, **kwargs):\n        pipeline = Pipeline.current()\n        if pipeline is None:\n            Pipeline._raise_no_current_pipeline(\"TorchPythonFunction\")\n        if self.stream is None:\n            self.stream = torch.cuda.Stream(device=pipeline.device_id)\n        return super(TorchPythonFunction, self).__call__(*inputs, **kwargs)\n\n    def __init__(self, function, num_outputs=1, device='cpu', batch_processing=False, **kwargs):\n        self.stream = None\n        super(TorchPythonFunction, self).__init__(impl_name=\"DLTensorPythonFunctionImpl\",\n                                                  function=lambda *ins:\n                                                  self.torch_wrapper(batch_processing,\n                                                                     function, device,\n                                                                     *ins),\n                                                  num_outputs=num_outputs, device=device,\n                                                  batch_processing=batch_processing, **kwargs)\n\n\nops._wrap_op(TorchPythonFunction, \"fn\", __name__)","metadata":{"_kg_hide-input":true,"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:14:00.278248Z","iopub.execute_input":"2025-02-23T04:14:00.278676Z","iopub.status.idle":"2025-02-23T04:14:00.301718Z","shell.execute_reply.started":"2025-02-23T04:14:00.278639Z","shell.execute_reply":"2025-02-23T04:14:00.300577Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport sys\nsys.path.append(\"/kaggle/input/segmentation-models-pytorch-030/pytorch-image-models/\")\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport timm\nfrom torch.utils.data import DataLoader, Dataset\nfrom torch.utils.data.sampler import SequentialSampler\nimport numpy as np\nimport pydicom\nfrom typing import List\nimport gc\nfrom tqdm import tqdm\nfrom joblib import Parallel, delayed\nimport pandas as pd\nfrom torchvision.transforms.functional import resize, to_tensor\nfrom PIL import Image\nimport dicomsdl\nfrom glob import glob\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nimport cv2\n\nimport nvidia.dali.fn as fn\nimport nvidia.dali.types as types\nfrom nvidia.dali import pipeline_def\nfrom nvidia.dali.types import DALIDataType\nfrom pydicom.filebase import DicomBytesIO\nfrom nvidia.dali.plugin.pytorch import feed_ndarray, to_torch_type\nimport cv2\nimport shutil\nfrom pandarallel import pandarallel\nimport time\nfrom timm.models.resnet import resnet34d\n\ntorch.set_grad_enabled(False)\nn_jobs = os.cpu_count()\npandarallel.initialize(progress_bar=True, nb_workers=n_jobs)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:14:00.30329Z","iopub.execute_input":"2025-02-23T04:14:00.30369Z","iopub.status.idle":"2025-02-23T04:14:05.378173Z","shell.execute_reply.started":"2025-02-23T04:14:00.303659Z","shell.execute_reply":"2025-02-23T04:14:05.376977Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def get_transfer_syntax(file):\n    dcmfile = pydicom.dcmread(file)\n    return dcmfile.file_meta.TransferSyntaxUID\n\ndef convert_dicom_to_j2k(file, save_folder=\"\"):\n    patient_id = file.split(\"/\")[-2]\n    image_id = file.split(\"/\")[-1][:-4]\n    \n    #lejun: 2stage ensemble ; https://www.kaggle.com/code/davidcen/2stage-ensemble-1016/edit\n    dcmfile = pydicom.dcmread(file)\n\n    if dcmfile.file_meta.TransferSyntaxUID == '1.2.840.10008.1.2.4.90':\n        with open(file, 'rb') as fp:\n            raw = DicomBytesIO(fp.read())\n            ds = pydicom.dcmread(raw)\n        offset = ds.PixelData.find(b\"\\x00\\x00\\x00\\x0C\")  #<---- the jpeg2000 header info we're looking for\n        hackedbitstream = bytearray()\n        hackedbitstream.extend(ds.PixelData[offset:])\n        with open(save_folder + f\"{patient_id}_{image_id}.jp2\", \"wb\") as binary_file:\n            binary_file.write(hackedbitstream)\n            \n    if dcmfile.file_meta.TransferSyntaxUID == '1.2.840.10008.1.2.4.70':\n        with open(file, 'rb') as fp:\n            raw = DicomBytesIO(fp.read())\n            ds = pydicom.dcmread(raw)\n        offset = ds.PixelData.find(b\"\\xff\\xd8\\xff\\xe0\")  #<---- the jpeg lossless header info we're looking for\n        hackedbitstream = bytearray()\n        hackedbitstream.extend(ds.PixelData[offset:])\n        with open(save_folder + f\"{patient_id}_{image_id}.jp2\", \"wb\") as binary_file:\n            binary_file.write(hackedbitstream)\n            \n\n\n@pipeline_def\ndef j2k_decode_pipeline(j2kfiles):\n    jpegs, _ = fn.readers.file(files=j2kfiles)\n    images = fn.experimental.decoders.image(\n        jpegs, device=\"mixed\", output_type=types.ANY_DATA, dtype=DALIDataType.UINT16\n    )\n    return images\n\n\ndef non_j2k_decode(dicom_file: str):\n    data = dicomsdl.open(dicom_file)\n    img = data.pixelData()\n    min_, max_ = img.min(), img.max()\n    img = (img - min_) / (max_ - min_)\n    if data.PhotometricInterpretation == \"MONOCHROME1\":\n        img = 1 - img\n    img = (img * 255).astype(np.uint8)\n    img: Image.Image = resize(\n        Image.fromarray(img), (SIZE, int(img.shape[1] / img.shape[0] * SIZE)), antialias=True\n    )\n    patient_id = dicom_file.split(\"/\")[-2]\n    image_id = dicom_file.split(\"/\")[-1][:-4]\n    img.save(os.path.join(SAVE_FOLDER, f\"{patient_id}_{image_id}.png\"))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:14:05.379604Z","iopub.execute_input":"2025-02-23T04:14:05.380145Z","iopub.status.idle":"2025-02-23T04:14:05.394151Z","shell.execute_reply.started":"2025-02-23T04:14:05.380107Z","shell.execute_reply":"2025-02-23T04:14:05.393024Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#test_df = pd.read_csv('/kaggle/input/rsna-breast-cancer-detection/test.csv')\ntrain_df = pd.read_csv('/kaggle/input/rsna-breast-cancer-detection/train.csv')\n#train_df.drop(index=[16772, 16773, 16774, 16775, 16776, 53065], inplace=True)\n\n#train_df = train_df.loc[[33117,33118,33119,33120,33121,33122,33123]]\n\n#train_df = train_df.loc[[i for i in range(50000,54705+1)]]  # the end value is exclusive\ntrain_df = train_df.loc[[i for i in range(32620,32629+1)]]  # to get the patient id of 45003\n\n\ndisplay(train_df.head())\ndisplay(train_df.shape)\n\n#display(test_df.head())\n#display(test_df.shape)\n\nIMAGES_FOLDER = \"../input/rsna-breast-cancer-detection/train_images\"\nWEIGHTS_FOLDER = \"../input/rsns-2022-runs\"\nSAVE_FOLDER = \"/kaggle/working/png/\"\nos.makedirs(SAVE_FOLDER, exist_ok=True)\nJ2K_FOLDER = \"/tmp/j2k/\"\n\n#J2K_FOLDER = \"/kaggle/working/\"\nSIZE = 1536\nIMAGE_HEIGHT = 1536\nIMAGE_WIDTH = 1024\n\n\ntest_images = glob(f\"{IMAGES_FOLDER}/*/*.dcm\")  # IMAGES_FOLDER = \"../input/rsna-breast-cancer-detection/train_images\"\ntest_df = train_df\n\ntest_df[\"image\"] = IMAGES_FOLDER + \"/\" + test_df[\"patient_id\"].astype(str) + \"/\" + test_df[\"image_id\"].astype(str) + \".dcm\"\ntest_df[\"TransferSyntaxUID\"] = test_df[\"image\"].parallel_apply(\n        lambda x: get_transfer_syntax(x)\n    )\nj2k_images = test_df[test_df[\"TransferSyntaxUID\"] == \"1.2.840.10008.1.2.4.90\"][\n    \"image\"\n].values\nnon_j2k_images = test_df[test_df[\"TransferSyntaxUID\"] != \"1.2.840.10008.1.2.4.90\"][\n    \"image\"\n].values","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:14:05.395494Z","iopub.execute_input":"2025-02-23T04:14:05.395858Z","iopub.status.idle":"2025-02-23T04:16:04.511828Z","shell.execute_reply.started":"2025-02-23T04:14:05.395831Z","shell.execute_reply":"2025-02-23T04:16:04.5083Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"start = time.time()\nif len(j2k_images) > 100:\n    N_CHUNKS = 4\nelse:\n    N_CHUNKS = 1\nCHUNKS = [\n    (len(j2k_images) / N_CHUNKS * k, len(j2k_images) / N_CHUNKS * (k + 1))\n    for k in range(N_CHUNKS)\n]\nCHUNKS = np.array(CHUNKS).astype(int)\n\n#os.makedirs(J2K_FOLDER, exist_ok=True)\n#shutil.rmtree(J2K_FOLDER)\n#os.makedirs(J2K_FOLDER, exist_ok=True)\n\n\nfor chunk in tqdm(CHUNKS):\n    os.makedirs(J2K_FOLDER, exist_ok=True)\n    _ = Parallel(n_jobs=n_jobs)(\n        delayed(convert_dicom_to_j2k)(img, save_folder=J2K_FOLDER)\n        for img in j2k_images[chunk[0] : chunk[1]]\n    )\n\n    j2kfiles = glob(J2K_FOLDER + \"*.jp2\")\n    if len(j2kfiles) == 0:\n        continue\n    pipe = j2k_decode_pipeline(j2kfiles, batch_size=1, num_threads=2, device_id=0, debug=True)\n    pipe.build()\n    for i, f in enumerate(j2kfiles):\n        patient, image = f.split(\"/\")[-1][:-4].split(\"_\")\n        dicom = pydicom.dcmread(os.path.join(IMAGES_FOLDER, f\"{patient}/{image}.dcm\"))\n        # Dali -> Torch\n        out = pipe.run()\n        img = out[0][0]\n        img_torch = torch.empty(img.shape(), dtype=torch.int16, device=\"cuda\")\n        feed_ndarray(img, img_torch, cuda_stream=torch.cuda.current_stream(device=0))\n        img = img_torch.float()\n        # Scale, resize, invert on GPU !\n        min_, max_ = img.min(), img.max()\n        img = (img - min_) / (max_ - min_)\n        if dicom.PhotometricInterpretation == \"MONOCHROME1\":\n            img = 1 - img\n        img = img * 255\n\n        img = resize(\n            img.view(1, 1, img.shape[0], img.shape[1]),\n            (SIZE, int(img.shape[1] / img.shape[0] * SIZE)),\n            antialias=True,\n        )[0, 0]\n        # Back to CPU + SAVE\n        img = img.cpu().numpy().astype(np.uint8)\n        cv2.imwrite(SAVE_FOLDER + f\"{patient}_{image}.png\", img)\n    shutil.rmtree(J2K_FOLDER)\nend = time.time()\nprint(f\"Num. JPEG2000 files: {len(j2k_images)} - processing time: {end - start} seconds\")\n\nstart = time.time()\n_ = Parallel(n_jobs=n_jobs)(delayed(non_j2k_decode)(img) for img in tqdm(non_j2k_images))\nend = time.time()\nprint(\n    f\"Num. non-JPEG2000 files: {len(non_j2k_images)} - processing time: {end - start} seconds\"\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:16:04.51495Z","iopub.execute_input":"2025-02-23T04:16:04.519548Z","iopub.status.idle":"2025-02-23T04:16:10.777195Z","shell.execute_reply.started":"2025-02-23T04:16:04.519486Z","shell.execute_reply":"2025-02-23T04:16:10.775935Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#assert len(os.listdir(SAVE_FOLDER)) != (len(non_j2k_images) + len(j2k_images))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:16:10.778785Z","iopub.execute_input":"2025-02-23T04:16:10.779126Z","iopub.status.idle":"2025-02-23T04:16:10.784164Z","shell.execute_reply.started":"2025-02-23T04:16:10.779093Z","shell.execute_reply":"2025-02-23T04:16:10.783075Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Predict masks","metadata":{}},{"cell_type":"code","source":"class CustomDataset(Dataset):\n    def __init__(self, path_list, input_size=512):\n        self.path_list = path_list\n        self.input_size = input_size\n\n    def __len__(self):\n        return len(self.path_list)\n\n    def __getitem__(self, i):\n        image = cv2.imread(self.path_list[i])\n        image, ratio = preproc(image, self.input_size)\n        image = torch.from_numpy(image)\n        return image, ratio, self.path_list[i]\n\n\ndef collate_fn(batch):\n    imgs = torch.stack([item[0] for item in batch])\n    ratios = [item[1] for item in batch]\n    paths = [item[2] for item in batch]\n    return imgs, ratios, paths","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:16:10.787816Z","iopub.execute_input":"2025-02-23T04:16:10.788137Z","iopub.status.idle":"2025-02-23T04:16:10.798027Z","shell.execute_reply.started":"2025-02-23T04:16:10.788103Z","shell.execute_reply":"2025-02-23T04:16:10.797135Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from yolox.exp import get_exp\nfrom yolox.utils import fuse_model, postprocess\nfrom yolox.data.data_augment import preproc\n\n\nclass Predictor:\n    def __init__(self, cls_names=(\"breast\"), device=\"cuda\", fp16=False):\n        exp = get_exp(\"../input/rsns-2022-runs/YOLOX/yolox_rsna.py\")\n        model = exp.get_model()\n        if device == \"cuda\":\n            model.cuda()\n        if fp16:\n            model = model.half()\n        model.eval()\n        ckpt_file = \"../input/rsns-2022-runs/YOLOX/YOLOX_outputs/yolox_rsna/best_ckpt.pth\"\n        ckpt = torch.load(ckpt_file, map_location=\"cpu\")\n        model.load_state_dict(ckpt[\"model\"])\n        model = fuse_model(model)\n#         if torch.cuda.device_count() > 1:\n#             model = nn.DataParallel(model)\n\n        self.device = device\n        self.model = model\n        self.num_classes = exp.num_classes\n        self.confthre = exp.test_conf\n        self.nmsthre = exp.nmsthre\n        self.test_size = exp.test_size\n        self.cls_names = cls_names\n\n    def __call__(self, imgs, ratios):\n        imgs = imgs.to(self.device, non_blocking=True)\n        with torch.no_grad():\n            outputs = self.model(imgs)\n        outputs = postprocess(\n            outputs,\n            self.num_classes,\n            self.confthre,\n            self.nmsthre,\n        )\n        outputs = self.rescale(outputs, ratios)\n        return outputs\n\n    def rescale(self, outputs, ratios):\n        rescaled_outputs = []\n        for output, ratio in zip(outputs, ratios):\n            if output is None:\n                rescaled_outputs.append(())\n            else:\n                output = output.cpu()\n                bboxes = output[:, 0:4]\n                # preprocessing: resize\n                bboxes /= ratio\n                cls = output[:, 6]\n                scores = output[:, 4] * output[:, 5]\n                rescaled_outputs.append((bboxes, scores, cls))\n        return rescaled_outputs\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:16:10.799227Z","iopub.execute_input":"2025-02-23T04:16:10.799526Z","iopub.status.idle":"2025-02-23T04:16:10.84894Z","shell.execute_reply.started":"2025-02-23T04:16:10.799501Z","shell.execute_reply":"2025-02-23T04:16:10.848042Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Predictor()\n\ndataset = CustomDataset(\n    [path for path in glob(f\"{SAVE_FOLDER}/**\", recursive=True) if path.endswith(\".png\")],\n    input_size=model.test_size,\n)\ndataloader = DataLoader(dataset, batch_size=32, num_workers=2, collate_fn=collate_fn)\n\ndf = []\nimg_paths = []\n\nfor images, ratios, paths in tqdm(dataloader):\n    outputs = model(images, ratios)\n    for output, orig_img, path in zip(outputs, images, paths):\n        if len(output) > 0:\n            xyxy = output[0].tolist()[0]\n            df.append(\n                pd.DataFrame(\n                    {\n                        \"xmin\": xyxy[0],\n                        \"ymin\": xyxy[1],\n                        \"xmax\": xyxy[2],\n                        \"ymax\": xyxy[3],\n                        \"confidence\": output[1][0].item(),\n                        \"class\": [0],\n                        \"name\": [\"breast\"],\n                    }\n                )\n            )\n            img_paths.append(path)\n        else:\n            print(\"Cannot detect \", path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:16:10.850058Z","iopub.execute_input":"2025-02-23T04:16:10.850331Z","iopub.status.idle":"2025-02-23T04:16:20.53268Z","shell.execute_reply.started":"2025-02-23T04:16:10.850306Z","shell.execute_reply":"2025-02-23T04:16:20.531337Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.concat(df).reset_index(drop=True).drop(columns=[\"class\", \"name\"])\ndf[\"png_file\"] = img_paths\ndf['key'] = df['png_file'].apply(lambda x: x.split('/')[-1].split('.')[0])\n\ntest_df[\"prediction_id\"] = test_df[\"patient_id\"].astype(str) + \"_\" + test_df[\"laterality\"].astype(str)\n\ntest_df['key'] = test_df['patient_id'].astype(str) + '_' + test_df['image_id'].astype(str)\n\n#display(test_df.head())\ndisplay(test_df)\ndisplay(test_df.shape)\n\ndf = df.merge(test_df[['key', 'laterality', 'view', \"patient_id\", \"image_id\", 'prediction_id']], on=['key'])\n# del model; gc.collect(); torch.cuda.empty_cache()python op","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:16:20.534291Z","iopub.execute_input":"2025-02-23T04:16:20.534668Z","iopub.status.idle":"2025-02-23T04:16:20.582271Z","shell.execute_reply.started":"2025-02-23T04:16:20.534635Z","shell.execute_reply":"2025-02-23T04:16:20.581046Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def read_img(path):\n    return np.array(Image.open(path))\n\nclass TestDataset(Dataset):\n    def __init__(self, df: pd.DataFrame):\n        super().__init__()\n        df[\"xmin\"] = df[\"xmin\"].clip(lower=0).astype(int)\n        df[\"xmax\"] = df[\"xmax\"].astype(int)\n        df[\"ymin\"] = df[\"ymin\"].clip(lower=0).astype(int)\n        df[\"ymax\"] = df[\"ymax\"].astype(int)\n        df[\"h\"] = df[\"ymax\"] - df[\"ymin\"]\n        df[\"w\"] = df[\"xmax\"] - df[\"xmin\"]\n        df = df.merge(\n            df.groupby(\"patient_id\")\n            .apply(lambda x: [x[\"h\"].max(), x[\"w\"].max()])\n            .to_frame(\"max_pad_breast_shape\")\n            .reset_index(),\n            on=[\"patient_id\"],\n        ).reset_index(drop=True)\n        self.df = df\n        self.image_height = IMAGE_HEIGHT\n        self.image_width = IMAGE_WIDTH\n        self.transform = A.Compose([A.Normalize(mean=0, std=1), ToTensorV2()])\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        info = self.df.iloc[idx]\n        img = read_img(info.png_file)\n        h, w = img.shape\n        image = np.zeros((self.image_height, self.image_width), np.uint8)\n        \n        xmin, ymin, xmax, ymax = info[\"xmin\"], info[\"ymin\"], info[\"xmax\"], info[\"ymax\"]\n        crop = img[ymin:ymax, xmin:xmax]\n        mh, mw = info[\"max_pad_breast_shape\"]\n        scale = min(self.image_height / mh, self.image_width / mw)\n        dsize = (\n            min(self.image_width, int(scale * crop.shape[1])),\n            min(self.image_height, int(scale * crop.shape[0])),\n        )\n        if dsize != (crop.shape[1], crop.shape[0]):\n            crop = cv2.resize(crop, dsize=dsize, interpolation=cv2.INTER_LINEAR)\n        ch, cw = crop.shape\n        x = (self.image_width - cw) // 2\n        y = (self.image_height - ch) // 2\n        image[y : y + ch, x : x + cw] = crop\n        image = self.transform(image=image)[\"image\"]\n\n        return image, info['prediction_id']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:16:20.584094Z","iopub.execute_input":"2025-02-23T04:16:20.584764Z","iopub.status.idle":"2025-02-23T04:16:20.600804Z","shell.execute_reply.started":"2025-02-23T04:16:20.584714Z","shell.execute_reply":"2025-02-23T04:16:20.599686Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torch.cuda.amp import autocast\n\nclass Efficientnet(nn.Module):\n    def __init__(self, model_name: str = \"base\"):\n        super().__init__()\n        self.backbone = timm.create_model(\n            model_name,\n            pretrained=False,\n            in_chans=1,\n            drop_path_rate=0.2,\n        )\n\n        feature_info = self.backbone.feature_info\n        self.block_out_idx = [1, 2, 4]\n\n        self.aux_block1 = nn.Sequential(\n            nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.BatchNorm1d(feature_info[1][\"num_chs\"])\n        )\n        self.aux_block2 = nn.Sequential(\n            nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.BatchNorm1d(feature_info[2][\"num_chs\"])\n        )\n        self.aux_block4 = nn.Sequential(\n            nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.BatchNorm1d(feature_info[3][\"num_chs\"])\n        )\n\n        self.aux_linear1 = nn.Linear(feature_info[1][\"num_chs\"], 1)\n        self.aux_linear2 = nn.Linear(feature_info[2][\"num_chs\"], 1)\n        self.aux_linear4 = nn.Linear(feature_info[3][\"num_chs\"], 1)\n        self.num_features = (\n            self.backbone.num_features\n            + feature_info[1][\"num_chs\"]\n            + feature_info[2][\"num_chs\"]\n            + feature_info[3][\"num_chs\"]\n        )\n        self.linear = nn.Linear(self.num_features, 1)\n\n    def forward_features(self, images: torch.Tensor):\n        x = self.backbone.conv_stem(images)\n        x = self.backbone.bn1(x)\n        features = []\n        for i, b in enumerate(self.backbone.blocks):\n            x = b(x)\n            if i in self.block_out_idx:\n                features.append(x)\n\n        features[0] = self.aux_block1(features[0])\n        features[1] = self.aux_block2(features[1])\n        features[2] = self.aux_block4(features[2])\n        features.append(self.backbone.global_pool(self.backbone.bn2(self.backbone.conv_head(x))))\n        return features\n\n    def forward(self, images: torch.Tensor):\n        features = self.forward_features(images)\n        features = torch.cat(features, 1)\n        logits = self.linear(features)\n        return logits\n\nclass Convnext(nn.Module):\n    def __init__(self, model_name: str):\n        super().__init__()\n\n        self.backbone: nn.Module = timm.create_model(\n            model_name,\n            in_chans=1,\n            pretrained=False,\n        )\n        self.backbone.reset_classifier(0, \"\")\n        self.num_features = self.backbone.num_features\n        self.linear = nn.Linear(self.num_features, 1)\n\n    def forward_features(self, images: torch.Tensor):\n        features = self.backbone(images)\n        features = features.mean(dim=(2, 3))\n        return features\n    \n    def forward(self, images: torch.Tensor):\n        features = self.forward_features(images)\n        logits = self.linear(features)\n        return logits","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:16:20.602386Z","iopub.execute_input":"2025-02-23T04:16:20.602951Z","iopub.status.idle":"2025-02-23T04:16:20.620899Z","shell.execute_reply.started":"2025-02-23T04:16:20.602914Z","shell.execute_reply":"2025-02-23T04:16:20.619857Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def create_models(timm_backbone=\"tf_efficientnetv2_s.in21k_ft_in1k\", exp_name=\"v2s\", model_cls=Efficientnet, num_folds=3):\n    models = []\n    for fold in range(num_folds):\n#    for fold in [0, 1, 2]:\n        cls_model = model_cls(timm_backbone)\n        ckpt_path = os.path.join(\"/kaggle/input/rsns-2022-runs\", f\"{exp_name}-fold{fold}/pytorch_model.bin\")\n        ckpt = torch.load(ckpt_path, \"cpu\")\n#         ckpt = {k.replace(\"_orig_mod.\", \"\"): v for k, v in ckpt.items()}\n#         ckpt = {k: v for k, v in ckpt.items() if not k.startswith(\"aug.\")}\n        cls_model.load_state_dict(ckpt)\n        cls_model.eval()\n        cls_model = cls_model.cuda()\n        print(f\"Loaded {ckpt_path}\")\n        \n        if torch.cuda.device_count() > 1:\n            models.append(nn.DataParallel(cls_model))\n        else:\n            models.append(cls_model)\n\n    return models","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:16:20.622072Z","iopub.execute_input":"2025-02-23T04:16:20.622448Z","iopub.status.idle":"2025-02-23T04:16:20.636264Z","shell.execute_reply.started":"2025-02-23T04:16:20.622419Z","shell.execute_reply":"2025-02-23T04:16:20.635098Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def predict(images, models):\n    probs = []\n    for model in models:\n        with torch.cuda.amp.autocast(enabled=True):\n            logits = model(images)\n        probs.append(torch.sigmoid(logits.view(-1)))\n    return torch.stack(probs, 0).mean(0)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:16:20.637756Z","iopub.execute_input":"2025-02-23T04:16:20.63819Z","iopub.status.idle":"2025-02-23T04:16:20.646286Z","shell.execute_reply.started":"2025-02-23T04:16:20.638156Z","shell.execute_reply":"2025-02-23T04:16:20.645189Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_dataset = TestDataset(df)\ntest_loader = DataLoader(test_dataset, batch_size=20, num_workers=2)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:16:20.648031Z","iopub.execute_input":"2025-02-23T04:16:20.648456Z","iopub.status.idle":"2025-02-23T04:16:20.669895Z","shell.execute_reply.started":"2025-02-23T04:16:20.648423Z","shell.execute_reply":"2025-02-23T04:16:20.668974Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"NUM_FOLDS = 5\n# THRESHOLD = 0.309\nTHRESHOLD = 0.299\nw1, w2 = 0.5982, 0.4018\nprint(THRESHOLD)\n\nv2s = create_models(\"tf_efficientnetv2_s.in21k_ft_in1k\", \"v2s-new\", Efficientnet, num_folds=NUM_FOLDS)\nb5 = create_models(\"tf_efficientnet_b5\", \"b5\", Efficientnet, num_folds=NUM_FOLDS)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:16:20.671464Z","iopub.execute_input":"2025-02-23T04:16:20.672228Z","iopub.status.idle":"2025-02-23T04:16:32.104505Z","shell.execute_reply.started":"2025-02-23T04:16:20.672184Z","shell.execute_reply":"2025-02-23T04:16:32.103332Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"patient_probs = []\npatient_probs_v2s = []\npatient_probs_b5 = []\nfor images, pred_ids in tqdm(test_loader):\n    images = images.half().cuda(non_blocking=True)\n    # probs = predict(images, v2s) * w1 + predict(images, b5) * w2\n\n    probs_v2s = predict(images, v2s)\n    probs_b5 = predict(images, b5)\n    probs = probs_v2s * w1 + probs_b5 * w2\n    \n    patient_probs.extend(probs.cpu().numpy().tolist())\n    patient_probs_v2s.extend(probs_v2s.cpu().numpy().tolist())\n    patient_probs_b5.extend(probs_b5.cpu().numpy().tolist())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:16:32.106048Z","iopub.execute_input":"2025-02-23T04:16:32.106422Z","iopub.status.idle":"2025-02-23T04:16:38.720533Z","shell.execute_reply.started":"2025-02-23T04:16:32.106387Z","shell.execute_reply":"2025-02-23T04:16:38.719205Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"del df; gc.collect()\ndf = test_dataset.df\n\ndf[\"cancer\"] = patient_probs\n#sub_df = df.groupby([\"prediction_id\"]).agg({\"cancer\": \"mean\"}).reset_index()\n#sub_df\n\ndf[\"v2s\"] = patient_probs_v2s\ndf[\"b5\"] = patient_probs_b5\n\nsub_df = df.groupby('prediction_id').agg({'cancer': 'mean', 'v2s': 'mean', 'b5': 'mean'}).reset_index()\nsub_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:16:38.72218Z","iopub.execute_input":"2025-02-23T04:16:38.722581Z","iopub.status.idle":"2025-02-23T04:16:38.986498Z","shell.execute_reply.started":"2025-02-23T04:16:38.722547Z","shell.execute_reply":"2025-02-23T04:16:38.985305Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sub_df[\"cancer\"] = (sub_df[\"cancer\"] > THRESHOLD).astype(int)\nsub_df.to_csv(\"submission_5_5f_raw_45kto50k.csv\", index=False)\nsub_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:16:38.988122Z","iopub.execute_input":"2025-02-23T04:16:38.988552Z","iopub.status.idle":"2025-02-23T04:16:39.009236Z","shell.execute_reply.started":"2025-02-23T04:16:38.988519Z","shell.execute_reply":"2025-02-23T04:16:39.008199Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#test_df[\"prediction_id\"] = test_df[\"patient_id\"].astype(str) + \"_\" + test_df[\"laterality\"].astype(str)\n\n#test_df['key'] = test_df['patient_id'].astype(str) + '_' + test_df['image_id'].astype(str)\n\ntest_df = test_df.groupby([\"prediction_id\"]).agg({\"cancer\": \"mean\"}).reset_index()\ntest_df[\"cancer\"] = test_df[\"cancer\"].astype(int)\n\n#test_df.at[0, 'cancer'] = 1\n\n#display(test_df.head())\ndisplay(test_df)\ndisplay(test_df.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:16:39.010657Z","iopub.execute_input":"2025-02-23T04:16:39.011574Z","iopub.status.idle":"2025-02-23T04:16:39.026244Z","shell.execute_reply.started":"2025-02-23T04:16:39.011531Z","shell.execute_reply":"2025-02-23T04:16:39.025244Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"mask = test_df[\"cancer\"] != sub_df[\"cancer\"]\ndifference =  test_df[mask]\n\ndisplay(difference)\ndisplay(difference.shape)\ndifference.to_csv(\"difference_5_5f_raw_45kto50k.csv\", index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-23T04:16:39.027931Z","iopub.execute_input":"2025-02-23T04:16:39.028752Z","iopub.status.idle":"2025-02-23T04:16:39.041407Z","shell.execute_reply.started":"2025-02-23T04:16:39.028721Z","shell.execute_reply":"2025-02-23T04:16:39.040345Z"}},"outputs":[],"execution_count":null}]}