{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"! pip install --no-deps /kaggle/input/keras-cv-attention-models/keras_cv_attention_models-1.3.5-py3-none-any.whl\n! pip install tensorrt --no-index --find-links \"/kaggle/input/tensorrt-packages\"\n! pip install tf2onnx","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","scrolled":true,"execution":{"iopub.status.busy":"2023-02-13T02:03:07.676157Z","iopub.execute_input":"2023-02-13T02:03:07.676688Z","iopub.status.idle":"2023-02-13T02:04:16.729469Z","shell.execute_reply.started":"2023-02-13T02:03:07.676625Z","shell.execute_reply":"2023-02-13T02:04:16.7283Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%capture\n# Source: https://www.kaggle.com/code/remekkinas/fast-dicom-processing-1-6-2x-faster?scriptVersionId=113360473\n!pip install /kaggle/input/rsnamodules/dicomsdl-0.109.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl \n\ntry:\n    import pylibjpeg\nexcept:\n   !pip install /kaggle/input/rsna-2022-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}","metadata":{"execution":{"iopub.status.busy":"2023-02-13T02:04:16.731881Z","iopub.execute_input":"2023-02-13T02:04:16.733541Z","iopub.status.idle":"2023-02-13T02:04:37.188469Z","shell.execute_reply.started":"2023-02-13T02:04:16.733497Z","shell.execute_reply":"2023-02-13T02:04:37.187125Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport pylibjpeg\nimport pydicom\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\n# For tensorrt\nimport tensorrt as trt\nimport cupy as cp\n\nfrom joblib import Parallel, delayed\nfrom tqdm.notebook import tqdm\nfrom multiprocessing import cpu_count\nfrom keras_cv_attention_models import convnext, efficientnet\n\nimport cv2\nimport glob\nimport importlib\nimport os\nimport joblib\nimport time\nimport dicomsdl\nimport gc\n\nimport multiprocessing as mp","metadata":{"execution":{"iopub.status.busy":"2023-02-13T02:04:37.190367Z","iopub.execute_input":"2023-02-13T02:04:37.191125Z","iopub.status.idle":"2023-02-13T02:04:45.175233Z","shell.execute_reply.started":"2023-02-13T02:04:37.191078Z","shell.execute_reply":"2023-02-13T02:04:45.174295Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gpus = tf.config.list_physical_devices('GPU')\nif gpus:\n    try:\n        # Currently, memory growth needs to be the same across GPUs\n        for gpu in gpus:\n            tf.config.experimental.set_memory_growth(gpu, True)\n        logical_gpus = tf.config.list_logical_devices('GPU')\n        print(len(gpus), \"Physical GPUs,\", len(logical_gpus), \"Logical GPUs\")\n    except RuntimeError as e:\n        # Memory growth must be set before GPUs have been initialized\n        print(e)\n","metadata":{"scrolled":true,"execution":{"iopub.status.busy":"2023-02-13T02:04:45.177764Z","iopub.execute_input":"2023-02-13T02:04:45.178348Z","iopub.status.idle":"2023-02-13T02:04:48.66824Z","shell.execute_reply.started":"2023-02-13T02:04:45.178318Z","shell.execute_reply":"2023-02-13T02:04:48.667026Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IS_INTERACTIVE = os.environ['KAGGLE_KERNEL_RUN_TYPE'] == 'Interactive'\n\nTARGET_HEIGHT = 1680\nTARGET_WIDTH = 960\nN_CHANNELS = 1\nINPUT_SHAPE = (TARGET_HEIGHT, TARGET_WIDTH, N_CHANNELS)\nTARGET_HEIGHT_WIDTH_RATIO = TARGET_HEIGHT / TARGET_WIDTH\nTHRESHOLD_BEST = 0.25\n\nCLAHE = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(32, 32))\n\nCROP_IMAGE = True\nAPPLY_CLAHE = False\nAPPLY_EQ_HIST = False\n\nIMAGE_FORMAT = 'jpg'\n\n# save processed images to disk\nOUTPUT_DIR = '/tmp/images'\ntry:\n    os.makedirs(OUTPUT_DIR)\nexcept:\n    pass","metadata":{"execution":{"iopub.status.busy":"2023-02-13T02:04:48.669964Z","iopub.execute_input":"2023-02-13T02:04:48.670724Z","iopub.status.idle":"2023-02-13T02:04:48.684954Z","shell.execute_reply.started":"2023-02-13T02:04:48.67068Z","shell.execute_reply":"2023-02-13T02:04:48.684209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Image preprocessing","metadata":{}},{"cell_type":"code","source":"# Source: https://www.kaggle.com/code/bobdegraaf/dicomsdl-voi-lut\ndef voi_lut(image, dicom):\n    # Additional Checks\n    if 'WindowWidth' not in dicom.getPixelDataInfo() or 'WindowWidth' not in dicom.getPixelDataInfo():\n        return image\n    \n    # Load only the variables we need\n    center = dicom['WindowCenter']\n    width = dicom['WindowWidth']\n    bits_stored = dicom['BitsStored']\n    voi_lut_function = dicom['VOILUTFunction']\n\n    # For sigmoid it's a list, otherwise a single value\n    if isinstance(center, list):\n        center = center[0]\n    if isinstance(width, list):\n        width = width[0]\n\n    # Set y_min, max & range\n    y_min = 0\n    y_max = float(2**bits_stored - 1)\n    y_range = y_max\n\n    # Function with default LINEAR (so for Nan, it will use linear)\n    if voi_lut_function == 'SIGMOID':\n        image = y_range / (1 + np.exp(-4 * (image - center) / width)) + y_min\n    else:\n        # Checks width for < 1 (in our case not necessary, always >= 750)\n        center -= 0.5\n        width -= 1\n\n        below = image <= (center - width / 2)\n        above = image > (center + width / 2)\n        between = np.logical_and(~below, ~above)\n\n        image[below] = y_min\n        image[above] = y_max\n        if between.any():\n            image[between] = (\n                ((image[between] - center) / width + 0.5) * y_range + y_min\n            )\n\n    return image\n\n# Smooth vector used to smoothen sums/stds of axes\ndef smooth(l):\n    # kernel size is 1% of vector\n    kernel_size = int(len(l) * 0.01)\n    kernel = np.ones(kernel_size) / kernel_size\n    return np.convolve(l, kernel, mode='same')\n\n# X Crop offset based on first column with sum below 5% of maximum column sums*std\ndef get_x_offset(image, max_col_sum_ratio_threshold=0.05, debug=None):\n    # Image Dimensions\n    H, W = image.shape\n    # Percentual margin added to offset\n    margin = int(image.shape[1] * 0.00)\n    # Threshold values based on smoothed sum x std to capture varying intensity columns\n    vv = smooth(image.sum(axis=0).squeeze()) * smooth(image.std(axis=0).squeeze())\n    # Find maximum sum in first 75% of columns\n    vv_argmax = vv[:int(image.shape[1] * 0.75)].argmax()\n    # Threshold value\n    vv_threshold = vv.max() * max_col_sum_ratio_threshold\n    \n    # Find first column after maximum column below threshold value\n    for offset, v in enumerate(vv):\n        # Start searching from vv_argmax\n        if offset < vv_argmax:\n            continue\n        \n        # Column below threshold value found\n        if v < vv_threshold:\n            offset = min(W, offset + margin)\n            break\n            \n    if isinstance(debug, np.ndarray):\n        debug[1].imshow(image)\n        debug[1].set_title('X Offset')\n        vv_scale = H / vv.max() * 0.90\n        # Values\n        debug[1].plot(H - vv * vv_scale , c='red', label='vv')\n        # Threshold\n        debug[1].hlines(H - vv_threshold * vv_scale, 0, W -1, colors='orange', label='threshold')\n        # Max Value\n        debug[1].scatter(vv_argmax, H - vv[vv_argmax] * vv_scale, c='blue', s=100, label='Max', zorder=np.PINF)\n        # First Column Below Threshold\n        debug[1].scatter(offset, H - vv[offset] * vv_scale, c='purple', s=100, label='Offset', zorder=np.PINF)\n        debug[1].set_ylim(H, 0)\n        debug[1].legend()\n        debug[1].axis('off')\n        \n    return offset\n\n# Y Crop offset based on first bottom and top rows with sum below 10% of maximum row sum*std\ndef get_y_offsets(image, max_row_sum_ratio_threshold=0.10, debug=None):\n    # Image Dimensions\n    H, W = image.shape\n    # Margin to add to offsets\n    margin = 0\n    # Threshold values based on smoothed sum x std to capture varying intensity columns\n    vv = smooth(image.sum(axis=1).squeeze()) * smooth(image.std(axis=1).squeeze())\n    # Find maximum sum * std row in inter quartile rows\n    vv_argmax = int(image.shape[0] * 0.25) + vv[int(image.shape[0] * 0.25):int(image.shape[0] * 0.75)].argmax()\n    # Threshold value\n    vv_threshold = vv.max() * max_row_sum_ratio_threshold\n    # Default crop offsets\n    offset_bottom = 0\n    offset_top = H\n\n    # Bottom offset, search from argmax to bottom\n    for offset in reversed(range(0, vv_argmax)):\n        v = vv[offset]\n        if v < vv_threshold:\n            offset_bottom = offset\n            break\n    \n    if isinstance(debug, np.ndarray):\n        debug[2].imshow(image)\n        debug[2].set_title('Y Bottom Offset')\n        vv_scale = W / vv.max() * 0.90\n        # Values\n        debug[2].plot(vv * vv_scale, np.arange(H), c='red', label='vv')\n        # Threshold\n        debug[2].vlines(vv_threshold * vv_scale, 0, H -1, colors='orange', label='threshold')\n        # Max Value\n        debug[2].scatter(vv[vv_argmax] * vv_scale, vv_argmax, c='blue', s=100, label='Max', zorder=np.PINF)\n        # First Column Below Threshold\n        debug[2].scatter(vv[offset_bottom] * vv_scale, offset_bottom, c='purple', s=100, label='Offset', zorder=np.PINF)\n        debug[2].set_ylim(H, 0)\n        debug[2].legend()\n        debug[2].axis('off')\n            \n    # Top offset, search from argmax to top\n    for offset in range(vv_argmax, H):\n        v = vv[offset]\n        if v < vv_threshold:\n            offset_top = offset\n            break\n            \n    if isinstance(debug, np.ndarray):\n        debug[3].imshow(image)\n        debug[3].set_title('Y Top Offset')\n        vv_scale = W / vv.max() * 0.90\n        # Values\n        debug[3].plot(vv * vv_scale, np.arange(H) , c='red', label='vv')\n        # Threshold\n        debug[3].vlines(vv_threshold * vv_scale, 0, H -1, colors='orange', label='threshold')\n        # Max Value\n        debug[3].scatter(vv[vv_argmax] * vv_scale, vv_argmax, c='blue', s=100, label='Max', zorder=np.PINF)\n        # First Column Below Threshold\n        debug[3].scatter(vv[offset_top] * vv_scale, offset_top, c='purple', s=100, label='Offset', zorder=np.PINF)\n        debug[2].set_ylim(H, 0)\n        debug[3].legend()\n        debug[3].axis('off')\n            \n    return max(0, offset_bottom - margin), min(image.shape[0], offset_top + margin)\n\n# Crop image and pad offsets to target image height/width ratio to preserve information\ndef crop(image, size=None, debug=False):\n    # Image dimensions\n    H, W = image.shape\n    # Compute x/bottom/top offsets\n    x_offset = get_x_offset(image, debug=debug)\n    offset_bottom, offset_top = get_y_offsets(image[:,:x_offset], debug=debug)\n    # Crop Height and Width\n    h_crop = offset_top - offset_bottom\n    w_crop = x_offset\n    \n    # Pad crop offsets to target aspect ratio\n    if size is not None:\n        # Height too large, pad x offset\n        if (h_crop / w_crop) > TARGET_HEIGHT_WIDTH_RATIO:\n            x_offset += int(h_crop / TARGET_HEIGHT_WIDTH_RATIO - w_crop)\n        else:\n            # Height too small, pad bottom/top offsets\n            offset_bottom -= int(0.50 * (w_crop * TARGET_HEIGHT_WIDTH_RATIO - h_crop))\n            offset_bottom_correction = max(0, -offset_bottom)\n            offset_bottom += offset_bottom_correction\n\n            offset_top += int(0.50 * (w_crop * TARGET_HEIGHT_WIDTH_RATIO - h_crop))\n            offset_top += offset_bottom_correction\n        \n    # Crop Image\n    image = image[offset_bottom:offset_top:,:x_offset]\n        \n    return image\n\ndef process(file_path, size=(TARGET_WIDTH, TARGET_HEIGHT), crop_image=CROP_IMAGE, apply_clahe=APPLY_CLAHE, apply_eq_hist=APPLY_EQ_HIST, debug=False, save=True):\n    # Read Dicom File\n    dicom = dicomsdl.open(file_path)\n    image = dicom.pixelData()\n    \n    # Save original image for debug purposes\n    if debug:\n        fig, axes = plt.subplots(1, 5, figsize=(20,10))\n        image0 = np.copy(image)\n        axes[0].imshow(image0)\n        axes[0].set_title('Original Image')\n        axes[0].axis('off')\n    else:\n        axes = False\n    \n    # voi_lut\n    try:\n        image = voi_lut(image, dicom)\n    except:\n        pass\n    \n    # Some images have 0 values as highest intensity and need to be inverted\n    if dicom.getPixelDataInfo()['PhotometricInterpretation'] == 'MONOCHROME1':\n        image = np.max(image) - image\n\n    # Normalize [0,1] range\n    image = (image - image.min()) / (image.max() - image.min())\n\n    # Convert to uint8 image in range [0, 255]\n    image = (image * 255).astype(np.uint8)\n    \n    # Flip T0 Left/Right Orientation\n    h0, w0 = image.shape\n    if image[:,int(-w0 * 0.10):].sum() > image[:,:int(w0 * 0.10)].sum():\n        image = np.flip(image, axis=1)\n    \n    # Crop Image\n    if crop_image:\n        image = crop(image, debug=axes)\n        \n    # Resize\n    if size is not None:\n        # Pad black pixels to make square image\n        h, w = image.shape\n        if (h / w) > TARGET_HEIGHT_WIDTH_RATIO:\n            pad = int(h / TARGET_HEIGHT_WIDTH_RATIO - w)\n            image = np.pad(image, [[0,0], [0, pad]])\n            h, w = image.shape\n        else:\n            pad = int(0.50 * (w * TARGET_HEIGHT_WIDTH_RATIO - h))\n            image = np.pad(image, [[pad, pad], [0,0]])\n            h, w = image.shape\n        # Resize\n        image = cv2.resize(image, size, interpolation=cv2.INTER_AREA)\n        \n    # Apply CLAHE contrast enhancement\n    if apply_clahe:\n        image = CLAHE.apply(image)\n        \n     # Apply Histogram Equalization\n    if apply_eq_hist:\n        image = cv2.equalizeHist(image)\n        \n    # Show Processed Image    \n    if debug:\n        axes[4].imshow(image)\n        axes[4].set_title('Processed Image')\n        axes[4].axis('off')\n        plt.show()\n        \n    # Save Only\n    if save:\n        image_id = file_path.split('/')[-1].split('.')[0]\n        if IMAGE_FORMAT == 'png':\n            cv2.imwrite(f'{OUTPUT_DIR}/{image_id}.png', image)\n        else:\n            cv2.imwrite(f'{OUTPUT_DIR}/{image_id}.jpg', image, [cv2.IMWRITE_JPEG_QUALITY, 95])","metadata":{"execution":{"iopub.status.busy":"2023-02-13T02:04:48.686584Z","iopub.execute_input":"2023-02-13T02:04:48.687211Z","iopub.status.idle":"2023-02-13T02:04:48.729196Z","shell.execute_reply.started":"2023-02-13T02:04:48.687174Z","shell.execute_reply":"2023-02-13T02:04:48.728473Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def normalize(image):\n    # Repeat channels to create 3 channel images required by pretrained ConvNextV2 models\n    image = tf.repeat(image, repeats=3, axis=3)\n    # Cast to float 32\n    image = tf.cast(image, tf.float32)\n    # Normalize with respect to ImageNet mean/std\n    image = tf.keras.applications.imagenet_utils.preprocess_input(image, mode='torch')\n\n    return image\n\ndef get_model(path):\n    # Inputs, note the names are equal to the dictionary keys in the dataset\n    image = tf.keras.layers.Input(INPUT_SHAPE, name='image', dtype=tf.float32)\n\n    # Normalize Input\n    image_norm = normalize(image)\n\n    # CNN Feature Maps\n#     x = convnext.ConvNeXtV2Tiny(\n#         input_shape=(TARGET_HEIGHT, TARGET_WIDTH, 3),\n#         pretrained=None,\n#         num_classes=0,\n#     )(image_norm)\n\n    x = efficientnet.EfficientNetV1B0(\n        input_shape=(TARGET_HEIGHT, TARGET_WIDTH, 3),\n        pretrained=None,\n        num_classes=0,\n    )(image_norm)\n\n    # Average Pooling BxHxWxC -> BxC\n    x = tf.keras.layers.GlobalAveragePooling2D()(x)\n    # Dropout to prevent Overfitting\n    x = tf.keras.layers.Dropout(0.10)(x)\n    # Output value between [0, 1] using Sigmoid function\n    outputs = tf.keras.layers.Dense(1, activation='sigmoid')(x)\n\n    # Define model with inputs and outputs\n    model = tf.keras.models.Model(inputs=image, outputs=outputs)\n\n    # Load pretrained Model Weights\n    model.load_weights(path)\n\n    # Set model non-trainable\n    model.trainable = False\n\n    # Compile model\n    model.compile()\n\n    return model","metadata":{"execution":{"iopub.status.busy":"2023-02-13T02:04:48.730639Z","iopub.execute_input":"2023-02-13T02:04:48.731284Z","iopub.status.idle":"2023-02-13T02:04:48.744375Z","shell.execute_reply.started":"2023-02-13T02:04:48.731234Z","shell.execute_reply":"2023-02-13T02:04:48.743373Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in range(10):\n    model = get_model(f'/kaggle/input/effnet-v2s-10-fold-models/model_fold_{i}.h5')\n    # save everything\n    tf.saved_model.save(model, f'/tmp/tf_models/model_{i}.pb')","metadata":{"execution":{"iopub.status.busy":"2023-02-13T02:04:48.745934Z","iopub.execute_input":"2023-02-13T02:04:48.746361Z","iopub.status.idle":"2023-02-13T02:11:07.353598Z","shell.execute_reply.started":"2023-02-13T02:04:48.746327Z","shell.execute_reply":"2023-02-13T02:11:07.352321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls /tmp/tf_models","metadata":{"execution":{"iopub.status.busy":"2023-02-13T02:11:07.362146Z","iopub.execute_input":"2023-02-13T02:11:07.362472Z","iopub.status.idle":"2023-02-13T02:11:08.64557Z","shell.execute_reply.started":"2023-02-13T02:11:07.362443Z","shell.execute_reply":"2023-02-13T02:11:08.644392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# convert tf2 model to onnx","metadata":{}},{"cell_type":"code","source":"!mkdir /tmp/onnx_models","metadata":{"execution":{"iopub.status.busy":"2023-02-13T02:11:08.652508Z","iopub.execute_input":"2023-02-13T02:11:08.652837Z","iopub.status.idle":"2023-02-13T02:11:09.706452Z","shell.execute_reply.started":"2023-02-13T02:11:08.652806Z","shell.execute_reply":"2023-02-13T02:11:09.705146Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!python -m tf2onnx.convert --saved-model /tmp/tf_models/model_0.pb --output /tmp/onnx_models/model_0.onnx\n!python -m tf2onnx.convert --saved-model /tmp/tf_models/model_1.pb --output /tmp/onnx_models/model_1.onnx\n!python -m tf2onnx.convert --saved-model /tmp/tf_models/model_2.pb --output /tmp/onnx_models/model_2.onnx\n!python -m tf2onnx.convert --saved-model /tmp/tf_models/model_3.pb --output /tmp/onnx_models/model_3.onnx\n!python -m tf2onnx.convert --saved-model /tmp/tf_models/model_4.pb --output /tmp/onnx_models/model_4.onnx\n!python -m tf2onnx.convert --saved-model /tmp/tf_models/model_5.pb --output /tmp/onnx_models/model_5.onnx\n!python -m tf2onnx.convert --saved-model /tmp/tf_models/model_6.pb --output /tmp/onnx_models/model_6.onnx\n!python -m tf2onnx.convert --saved-model /tmp/tf_models/model_7.pb --output /tmp/onnx_models/model_7.onnx\n!python -m tf2onnx.convert --saved-model /tmp/tf_models/model_8.pb --output /tmp/onnx_models/model_8.onnx\n!python -m tf2onnx.convert --saved-model /tmp/tf_models/model_9.pb --output /tmp/onnx_models/model_9.onnx","metadata":{"scrolled":true,"execution":{"iopub.status.busy":"2023-02-13T02:11:09.708756Z","iopub.execute_input":"2023-02-13T02:11:09.709189Z","iopub.status.idle":"2023-02-13T02:14:56.162646Z","shell.execute_reply.started":"2023-02-13T02:11:09.709146Z","shell.execute_reply":"2023-02-13T02:14:56.161076Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# explicity define batch size","metadata":{}},{"cell_type":"code","source":"# explicity define batch size\nimport onnx\nBATCH_SIZE = 8\n\nfor i in range(10):\n    onnx_model = onnx.load_model(f'/tmp/onnx_models/model_{i}.onnx')\n    inputs = onnx_model.graph.input\n    for input in inputs:\n        dim1 = input.type.tensor_type.shape.dim[0]\n        dim1.dim_value = BATCH_SIZE\n        \n    model_name = f'/tmp/onnx_models/model_{i}.onnx'\n    onnx.save_model(onnx_model, model_name)","metadata":{"execution":{"iopub.status.busy":"2023-02-13T02:14:56.16491Z","iopub.execute_input":"2023-02-13T02:14:56.16536Z","iopub.status.idle":"2023-02-13T02:14:56.839224Z","shell.execute_reply.started":"2023-02-13T02:14:56.165317Z","shell.execute_reply":"2023-02-13T02:14:56.838118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# converting onnx to tensorrt engine","metadata":{}},{"cell_type":"code","source":"def onnx_to_trt(i):\n    logger = trt.Logger(min_severity=trt.ILogger.WARNING)\n    builder = trt.Builder(logger)\n    network = builder.create_network(flags=1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))\n    parser = trt.OnnxParser(network=network, logger=logger)\n    parser.parse_from_file(f'/tmp/onnx_models/model_{i}.onnx')\n    \n    builder_config = builder.create_builder_config()\n    # FP16 quantization doesn't work for convnext model\n    builder_config.set_flag(trt.BuilderFlag.FP16)\n    \n    engine = builder.build_engine(network, builder_config)\n    \n    serialized_engine = engine.serialize()\n    with open(f'/kaggle/working/model_{i}.eng', 'wb') as f:\n        f.write(serialized_engine)","metadata":{"execution":{"iopub.status.busy":"2023-02-13T02:14:56.841088Z","iopub.execute_input":"2023-02-13T02:14:56.8415Z","iopub.status.idle":"2023-02-13T02:14:56.852468Z","shell.execute_reply.started":"2023-02-13T02:14:56.841459Z","shell.execute_reply":"2023-02-13T02:14:56.85148Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in range(10):\n    onnx_to_trt(i)","metadata":{"execution":{"iopub.status.busy":"2023-02-13T02:14:56.853886Z","iopub.execute_input":"2023-02-13T02:14:56.854671Z","iopub.status.idle":"2023-02-13T03:36:41.338699Z","shell.execute_reply.started":"2023-02-13T02:14:56.854633Z","shell.execute_reply":"2023-02-13T03:36:41.337619Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# dataset","metadata":{}},{"cell_type":"code","source":"# get some samples from training set for testing\ntest = pd.read_csv('/kaggle/input/rsna-breast-cancer-detection/train.csv').head(128)\n\ndef get_file_path(args):\n    patient_id, image_id = args\n    return f'/kaggle/input/rsna-breast-cancer-detection/train_images/{patient_id}/{image_id}.dcm'\n    \ntest['file_path'] = test[['patient_id', 'image_id']].apply(get_file_path, axis=1)\n\n# remove views with too few samples\nvalid_views = {'MLO', 'CC'}\nis_valid_view = test['view'].isin(valid_views)\ntest = test.loc[is_valid_view, :]","metadata":{"scrolled":true,"execution":{"iopub.status.busy":"2023-02-13T03:36:41.340505Z","iopub.execute_input":"2023-02-13T03:36:41.341143Z","iopub.status.idle":"2023-02-13T03:36:41.508905Z","shell.execute_reply.started":"2023-02-13T03:36:41.341096Z","shell.execute_reply":"2023-02-13T03:36:41.507929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Preprocess all images in parallel using Joblib\njobs = [joblib.delayed(process)(fp) for fp in test['file_path']]\nSUBMISSION_ROWS = joblib.Parallel(\n    n_jobs=cpu_count(),\n    verbose=IS_INTERACTIVE,\n    backend='multiprocessing',\n    prefer='threads',\n)(jobs)","metadata":{"execution":{"iopub.status.busy":"2023-02-13T03:36:41.510339Z","iopub.execute_input":"2023-02-13T03:36:41.510718Z","iopub.status.idle":"2023-02-13T03:38:32.011293Z","shell.execute_reply.started":"2023-02-13T03:36:41.510682Z","shell.execute_reply":"2023-02-13T03:38:32.010161Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 2x GPU inference","metadata":{}},{"cell_type":"code","source":"# Batch size per gpu\nBATCH_SIZE = 8","metadata":{"execution":{"iopub.status.busy":"2023-02-13T03:38:32.043492Z","iopub.execute_input":"2023-02-13T03:38:32.043841Z","iopub.status.idle":"2023-02-13T03:38:32.112712Z","shell.execute_reply.started":"2023-02-13T03:38:32.043807Z","shell.execute_reply":"2023-02-13T03:38:32.111624Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from ctypes import cdll, c_char_p\nlibcudart = cdll.LoadLibrary('libcudart.so')\nlibcudart.cudaGetErrorString.restype = c_char_p\n\ndef get_context(device_idx, eng_path):\n    # set the cuda device to create the context on\n    ret = libcudart.cudaSetDevice(device_idx)\n    if ret != 0:\n        error_string = libcudart.cudaGetErrorString(ret)\n        raise RuntimeError(\"cudaSetDevice: \" + error_string)\n    \n    # load engine and create the tensorrt context from the engine\n    logger = trt.Logger(min_severity=trt.ILogger.WARNING)\n    runtime = trt.Runtime(logger)\n    serialized_engine = open(eng_path, 'rb').read()\n    engine = runtime.deserialize_cuda_engine(serialized_engine)\n    context = engine.create_execution_context()\n    \n    return context\n\n# create tensorflow pipeline for loading images\ndef load_img(image_path):\n    image = tf.io.read_file(image_path)\n    image = tf.io.decode_jpeg(image)\n    return image\n\ndef pipeline(image_path):\n    image = load_img(image_path)\n    return image\n\ndef get_tf_pipeline(img_paths):\n    test_ds = tf.data.Dataset.from_tensor_slices(img_paths)\n    test_ds = test_ds.map(\n        pipeline, \n        num_parallel_calls=tf.data.AUTOTUNE).batch(BATCH_SIZE)\n    return test_ds\n\ndef get_preds(context, gpu_id, test_ds):\n    # set gpu to allocate data to for cupy\n    with cp.cuda.Device(gpu_id):\n        all_preds = []\n        for batch in test_ds:\n            batch = batch.numpy()\n            bs = len(batch)\n            if bs != BATCH_SIZE:\n                batch = np.pad(batch, ((0,BATCH_SIZE-len(batch)),(0,0),(0,0),(0,0)), 'constant', constant_values=0)\n            batch = batch.astype(np.float32)\n            \n            # Allocate memory on the GPU\n            input_data = cp.array(batch, dtype=np.float32)\n            output_data = cp.empty((BATCH_SIZE, 1), dtype=np.float32)\n            bindings = [input_data.data.ptr, output_data.data.ptr]\n\n            # Start inference\n            context.execute_v2(bindings)\n            preds = output_data.get()\n            all_preds.extend(preds.squeeze()[:bs])\n            \n    return all_preds\n\ndef run_inference_on_gpu(gpu_id, img_paths):\n    # create tensorflow image loading pipeline for images\n    test_ds = get_tf_pipeline(img_paths)\n    all_preds = []\n    for i in range(10):\n        # get the context from the engine file\n        context = get_context(gpu_id, f'/kaggle/working/model_{i}.eng')\n        # get predictions for current context and dataset\n        context_preds = get_preds(context, gpu_id, test_ds)\n        all_preds.append(context_preds)\n        \n    all_preds = np.array(all_preds)\n    all_preds.mean(0)\n\n    return all_preds","metadata":{"execution":{"iopub.status.busy":"2023-02-13T03:38:32.127551Z","iopub.execute_input":"2023-02-13T03:38:32.127836Z","iopub.status.idle":"2023-02-13T03:38:32.189387Z","shell.execute_reply.started":"2023-02-13T03:38:32.12781Z","shell.execute_reply":"2023-02-13T03:38:32.188453Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Divide the image paths into halves\ntest['processed_img_path'] = test['image_id'].apply(lambda x: f'{OUTPUT_DIR}/{x}.{IMAGE_FORMAT}')\nsplit_point = len(test['processed_img_path']) // 2\nimg_paths_1 = test['processed_img_path'][:split_point].values\nimg_paths_2 = test['processed_img_path'][split_point:].values","metadata":{"execution":{"iopub.status.busy":"2023-02-13T03:38:32.19088Z","iopub.execute_input":"2023-02-13T03:38:32.192759Z","iopub.status.idle":"2023-02-13T03:38:32.206067Z","shell.execute_reply.started":"2023-02-13T03:38:32.192723Z","shell.execute_reply":"2023-02-13T03:38:32.205132Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\njobs = [joblib.delayed(run_inference_on_gpu)(gpu_id, img_paths) for gpu_id, img_paths in [(0, img_paths_1), (1, img_paths_2)]]\npreds = joblib.Parallel(\n    n_jobs=2,\n    verbose=True,\n    prefer='threads',\n)(jobs)","metadata":{"execution":{"iopub.status.busy":"2023-02-13T03:38:32.207586Z","iopub.execute_input":"2023-02-13T03:38:32.208047Z","iopub.status.idle":"2023-02-13T03:38:56.511199Z","shell.execute_reply.started":"2023-02-13T03:38:32.208013Z","shell.execute_reply":"2023-02-13T03:38:56.510304Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(np.array(preds).flatten())","metadata":{"execution":{"iopub.status.busy":"2023-02-13T03:38:56.512485Z","iopub.execute_input":"2023-02-13T03:38:56.512844Z","iopub.status.idle":"2023-02-13T03:38:56.872369Z","shell.execute_reply.started":"2023-02-13T03:38:56.512808Z","shell.execute_reply":"2023-02-13T03:38:56.871487Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}