{"cells":[{"metadata":{},"cell_type":"markdown","source":"## Install dependencies (`pip`, `pytorch-lightning`, and `l5kit`)"},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install --no-index -f ../input/l5kitwithpytorchlightning pip==20.2.3","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip uninstall -y typing\n!pip install -q --no-index -f ../input/l5kitwithpytorchlightning l5kit==1.1 pytorch-lightning==0.10.0","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Make sure we have the correct version"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import l5kit\nimport torch\nimport torchvision\nimport pytorch_lightning as pl\nl5kit.__version__, torch.__version__, torchvision.__version__, pl.__version__, torch.cuda.is_available()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Custom evaluation functions\n\nFrom [this notebook](https://www.kaggle.com/corochann/lyft-pytorch-implementation-of-evaluation-metric)"},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport torch\nfrom l5kit.geometry import transform_points\nfrom torch import Tensor\n\n\ndef convert_agent_coordinates_to_world_offsets(\n    agents_coords: np.ndarray,\n    world_from_agents: np.ndarray,\n    centroids: np.ndarray,\n) -> np.ndarray:\n    coords_offset = []\n    for agent_coords, world_from_agent, centroid in zip(\n        agents_coords, world_from_agents, centroids\n    ):\n        predition_offset = []\n        for agent_coord in agent_coords:\n            predition_offset.append(\n                transform_points(agent_coord, world_from_agent) - centroid[:2]\n            )\n        predition_offset = np.stack(predition_offset)\n        coords_offset.append(predition_offset)\n    return np.stack(coords_offset)\n\n\ndef pytorch_neg_multi_log_likelihood_batch(\n    gt: Tensor,\n    pred: Tensor,\n    confidences: Tensor,\n    avails: Tensor,\n) -> Tensor:\n    \"\"\"\n    Compute a negative log-likelihood for the multi-modal scenario.\n    log-sum-exp trick is used here to avoid underflow and overflow, For more information about it see:\n    https://en.wikipedia.org/wiki/LogSumExp#log-sum-exp_trick_for_log-domain_calculations\n    https://timvieira.github.io/blog/post/2014/02/11/exp-normalize-trick/\n    https://leimao.github.io/blog/LogSumExp/\n    Args:\n        gt (Tensor): array of shape (bs)x(time)x(2D coords)\n        pred (Tensor): array of shape (bs)x(modes)x(time)x(2D coords)\n        confidences (Tensor): array of shape (bs)x(modes) with a confidence for each mode in each sample\n        avails (Tensor): array of shape (bs)x(time) with the availability for each gt timestep\n    Returns:\n        Tensor: negative log-likelihood for this example, a single float number\n    \"\"\"\n    assert len(pred.shape) == 4, f\"expected 3D (MxTxC) array for pred, got {pred.shape}\"\n    batch_size, num_modes, future_len, num_coords = pred.shape\n\n    assert gt.shape == (\n        batch_size,\n        future_len,\n        num_coords,\n    ), f\"expected 2D (Time x Coords) array for gt, got {gt.shape}\"\n    assert confidences.shape == (\n        batch_size,\n        num_modes,\n    ), f\"expected 1D (Modes) array for confidences, got {confidences.shape}\"\n    assert torch.allclose(\n        torch.sum(confidences, dim=1), confidences.new_ones((batch_size,))\n    ), \"confidences should sum to 1\"\n    assert avails.shape == (\n        batch_size,\n        future_len,\n    ), f\"expected 1D (Time) array for avails, got {avails.shape}\"\n    # assert all data are valid\n    assert torch.isfinite(pred).all(), \"invalid value found in pred\"\n    assert torch.isfinite(gt).all(), \"invalid value found in gt\"\n    assert torch.isfinite(confidences).all(), \"invalid value found in confidences\"\n    assert torch.isfinite(avails).all(), \"invalid value found in avails\"\n\n    # convert to (batch_size, num_modes, future_len, num_coords)\n    gt = torch.unsqueeze(gt, 1)  # add modes\n    avails = avails[:, None, :, None]  # add modes and cords\n\n    # error (batch_size, num_modes, future_len)\n    error = torch.sum(\n        ((gt - pred) * avails) ** 2, dim=-1\n    )  # reduce coords and use availability\n\n    with np.errstate(\n        divide=\"ignore\"\n    ):  # when confidence is 0 log goes to -inf, but we're fine with it\n        # error (batch_size, num_modes)\n        error = torch.log(confidences) - 0.5 * torch.sum(error, dim=-1)  # reduce time\n\n    # use max aggregator on modes for numerical stability\n    # error (batch_size, num_modes)\n    max_value, _ = error.max(\n        dim=1, keepdim=True\n    )  # error are negative at this point, so max() gives the minimum one\n    error = (\n        -torch.log(torch.sum(torch.exp(error - max_value), dim=-1, keepdim=True))\n        - max_value\n    )  # reduce modes\n    # print(\"error\", error)\n    return torch.mean(error)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Dataset definitions"},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nfrom typing import Dict, Optional\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pytorch_lightning as pl\nfrom l5kit.data import ChunkedDataset, LocalDataManager\nfrom l5kit.dataset import AgentDataset\nfrom l5kit.geometry import transform_points\nfrom l5kit.rasterization import build_rasterizer\nfrom l5kit.visualization import TARGET_POINTS_COLOR, draw_trajectory\nfrom torch.utils.data import DataLoader\n\nis_kaggle = os.path.isdir(\"/kaggle\")\n\n\ndata_root = (\n    \"/kaggle/input/lyft-motion-prediction-autonomous-vehicles\"\n    if is_kaggle\n    else \"lyft-motion-prediction-autonomous-vehicles\"\n)\n\n\nCONFIG_DATA = {\n    \"format_version\": 4,\n    \"model_params\": {\n        \"model_architecture\": \"resnet50\",\n        \"history_num_frames\": 0,\n        \"history_step_size\": 1,\n        \"history_delta_time\": 0.1,\n        \"future_num_frames\": 50,\n        \"future_step_size\": 1,\n        \"future_delta_time\": 0.1,\n    },\n    \"raster_params\": {\n        \"raster_size\": [256, 256],\n        \"pixel_size\": [0.5, 0.5],\n        \"ego_center\": [0.25, 0.5],\n        \"map_type\": \"py_semantic\",\n        \"satellite_map_key\": \"aerial_map/aerial_map.png\",\n        \"semantic_map_key\": \"semantic_map/semantic_map.pb\",\n        \"dataset_meta_key\": \"meta.json\",\n        \"filter_agents_threshold\": 0.5,\n        \"disable_traffic_light_faces\": False,\n    },\n    \"train_dataloader\": {\n        \"key\": \"scenes/train.zarr\",\n        \"batch_size\": 16,\n        \"shuffle\": True,\n        \"num_workers\": 4,\n    },\n    \"val_dataloader\": {\n        \"key\": \"scenes/validate.zarr\",\n        \"batch_size\": 16,\n        \"shuffle\": False,\n        \"num_workers\": 4,\n    },\n    \"test_dataloader\": {\n        \"key\": \"scenes/test.zarr\",\n        \"batch_size\": 16,\n        \"shuffle\": False,\n        \"num_workers\": 4,\n    },\n    \"train_params\": {\n        \"checkpoint_every_n_steps\": 10000,\n        \"max_num_steps\": 5,\n        \"eval_every_n_steps\": 10000,\n    },\n}\n\n\nclass LyftAgentDataModule(pl.LightningDataModule):\n    def __init__(\n        self,\n        cfg: Dict = CONFIG_DATA,\n        data_root: str = data_root,\n    ):\n        super().__init__()\n        self.cfg = cfg\n        self.dm = LocalDataManager(data_root)\n        self.rast = build_rasterizer(self.cfg, self.dm)\n        # self.ego_dataset = EgoDataset(self.cfg, self.zarr_dataset, self.rast)\n\n    def chunked_dataset(self, key: str):\n        dl_cfg = self.cfg[key]\n        dataset_path = self.dm.require(dl_cfg[\"key\"])\n        zarr_dataset = ChunkedDataset(dataset_path)\n        zarr_dataset.open()\n        return zarr_dataset\n\n    def get_dataloader_by_key(\n        self, key: str, mask: Optional[np.ndarray] = None\n    ) -> DataLoader:\n        dl_cfg = self.cfg[key]\n        zarr_dataset = self.chunked_dataset(key)\n        agent_dataset = AgentDataset(\n            self.cfg, zarr_dataset, self.rast, agents_mask=mask\n        )\n        return DataLoader(\n            agent_dataset,\n            shuffle=dl_cfg[\"shuffle\"],\n            batch_size=dl_cfg[\"batch_size\"],\n            num_workers=dl_cfg[\"num_workers\"],\n            pin_memory=True,\n        )\n\n    def train_dataloader(self):\n        key = \"train_dataloader\"\n        return self.get_dataloader_by_key(key)\n\n    def val_dataloader(self):\n        key = \"val_dataloader\"\n        return self.get_dataloader_by_key(key)\n\n    def test_dataloader(self):\n        key = \"test_dataloader\"\n        test_mask = np.load(f\"{data_root}/scenes/mask.npz\")[\"arr_0\"]\n        return self.get_dataloader_by_key(key, mask=test_mask)\n\n    def plt_show_agent_map(self, idx):\n        data = self.agent_dataset[idx]\n        im = data[\"image\"].transpose(1, 2, 0)\n        im = self.rast.to_rgb(im)\n        target_positions_pixels = transform_points(\n            data[\"target_positions\"] + data[\"centroid\"][:2], data[\"world_to_image\"]\n        )\n        draw_trajectory(\n            im, target_positions_pixels, data[\"target_yaws\"], TARGET_POINTS_COLOR\n        )\n        plt.imshow(im[::-1])\n        plt.show()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Model definition"},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nfrom typing import Dict\n\nimport numpy as np\nimport pytorch_lightning as pl\nimport torch\nfrom l5kit.evaluation.csv_utils import write_pred_csv\nfrom pytorch_lightning.callbacks import ModelCheckpoint\nfrom torch import nn, optim\nfrom torchvision.models.resnet import resnet18, resnet34, resnet50\nfrom tqdm.notebook import tqdm\n\ntry:\n    from jiayu_model.data_module import LyftAgentDataModule\n    from jiayu_model.loss_function import (\n        convert_agent_coordinates_to_world_offsets,\n        pytorch_neg_multi_log_likelihood_batch,\n    )\nexcept:\n    pass\n\n\nclass BaselineModel(pl.LightningModule):\n    \"\"\"Our baseline is a simple resnet pretrained on imagenet.\n    We must replace the input and the final layer to address our requirements.\n    \"\"\"\n\n    resnet_builders = {\n        \"resnet18\": resnet18,\n        \"resnet34\": resnet34,\n        \"resnet50\": resnet50,\n    }\n    backbone_out_feature_counts = {\n        \"resnet18\": 512,\n        \"resnet34\": 512,\n        \"resnet50\": 2048,\n    }\n\n    def __init__(\n        self,\n        cfg: Dict,\n        learning_rate=1e-3,\n        num_modes: int = 3,\n        pretrained=False,\n    ):\n        super().__init__()\n        self.save_hyperparameters()\n\n        cfg = self.hparams.cfg  # type: ignore\n        self.learning_rate = self.hparams.learning_rate  # type: ignore\n        self.num_modes = self.hparams.num_modes  # type: ignore\n        self.criterion = pytorch_neg_multi_log_likelihood_batch\n\n        model_architecture = cfg[\"model_params\"][\"model_architecture\"]\n        resnet_builder = BaselineModel.resnet_builders[model_architecture]\n        backbone_out_features = BaselineModel.backbone_out_feature_counts[\n            model_architecture\n        ]\n\n        resnet = resnet_builder(pretrained=pretrained)\n        # change input channels number to match the rasterizer's output\n        num_history_channels = (cfg[\"model_params\"][\"history_num_frames\"] + 1) * 2\n        num_in_channels = 3 + num_history_channels\n        resnet.conv1 = nn.Conv2d(\n            num_in_channels,\n            resnet.conv1.out_channels,\n            kernel_size=resnet.conv1.kernel_size,\n            stride=resnet.conv1.stride,\n            padding=resnet.conv1.padding,\n            bias=resnet.conv1.bias,\n        )\n        self.future_len = cfg[\"model_params\"][\"future_num_frames\"]\n        num_targets = 2 * self.future_len\n        self.num_preds = num_targets * self.num_modes\n        resnet.fc = nn.Sequential(\n            nn.Linear(\n                in_features=backbone_out_features,\n                # num of modes * preds + confidence\n                out_features=self.num_preds + self.num_modes,\n            ),\n        )\n        self.resnet = resnet\n\n    def forward(self, data):\n        out = self.resnet(data)\n        batch_size = data.shape[0]\n        pred, confidences = torch.split(out, self.num_preds, dim=1)\n        assert pred.shape == (batch_size, self.num_preds)\n        assert confidences.shape == (batch_size, self.num_modes)\n        pred = pred.view(batch_size, self.num_modes, self.future_len, 2)\n        confidences = torch.softmax(confidences, dim=1)\n        return pred, confidences\n\n    def configure_optimizers(self):\n        optimizer = optim.Adam(self.parameters(), lr=self.learning_rate)\n        return optimizer\n\n    def training_step(self, batch, batch_idx: int):  # type: ignore\n        target_availabilities = batch[\"target_availabilities\"]\n        targets = batch[\"target_positions\"]\n        data = batch[\"image\"]\n        pred, confidences = self(data)\n        loss = self.criterion(targets, pred, confidences, target_availabilities)\n        return loss\n\n    def validation_step(self, batch, batch_idx: int):  # type: ignore\n        target_availabilities = batch[\"target_availabilities\"]\n        targets = batch[\"target_positions\"]\n        data = batch[\"image\"]\n        pred, confidences = self(data)\n        loss = self.criterion(targets, pred, confidences, target_availabilities)\n        self.log(\"val_loss\", loss)\n\n\ndef train_model(\n    lyft_agent_data_module: LyftAgentDataModule,\n    max_epochs=5,\n    max_steps=30000,\n    fast_dev_run=True,\n) -> BaselineModel:\n    model = BaselineModel(cfg=lyft_agent_data_module.cfg)\n    checkpoint_callback = ModelCheckpoint(\n        filepath=os.getcwd(),\n        save_top_k=1,\n        verbose=True,\n        monitor=\"val_loss\",\n        mode=\"min\",\n    )\n    trainer = pl.Trainer(\n        gpus=1,\n        # tpu_cores=1,\n        precision=16,\n        max_epochs=max_epochs,\n        max_steps=max_steps,\n        checkpoint_callback=checkpoint_callback,\n        fast_dev_run=fast_dev_run,\n        val_check_interval=0.1,\n        limit_train_batches=max_steps // max_epochs,\n        limit_val_batches=200,\n    )\n    trainer.fit(model=model, datamodule=lyft_agent_data_module)\n    return model\n\n\ndef evaluation(checkpoint_path: str, lyft_agent_data_module: LyftAgentDataModule):\n    assert torch.cuda.is_available(), \"GPU must be used\"\n    device = torch.device(\"cuda\")\n    model = BaselineModel.load_from_checkpoint(checkpoint_path, map_location=device)\n    model = model.to(device)\n    model.eval()\n    model.freeze()\n\n    pred_coords_list = []\n    confidences_list = []\n    timestamps_list = []\n    track_id_list = []\n\n    for data in tqdm(lyft_agent_data_module.test_dataloader()):\n        pred, confidences = model(data[\"image\"].to(device))\n        pred = convert_agent_coordinates_to_world_offsets(\n            pred.detach().cpu().numpy(),\n            data[\"world_from_agent\"].numpy(),\n            data[\"centroid\"].numpy(),\n        )\n        pred_coords_list.append(pred)\n        confidences_list.append(confidences.detach().cpu().numpy())\n        timestamps_list.append(data[\"timestamp\"].detach().numpy())\n        track_id_list.append(data[\"track_id\"].detach().numpy())\n\n    timestamps = np.concatenate(timestamps_list)\n    track_ids = np.concatenate(track_id_list)\n    coords = np.concatenate(pred_coords_list)\n    confs = np.concatenate(confidences_list)\n\n    return timestamps, track_ids, coords, confs\n\n\nif __name__ == \"__main__\":\n    print(\"loading dataset\")\n    lyft_agent_data_module = LyftAgentDataModule()  # type: ignore\n\n    mode = \"evaluation\"\n\n    if mode == \"training\":\n        model_save_path = \"model_state_last.pth\"\n        print(\"dataset is loaded, starting training\")\n        model = train_model(lyft_agent_data_module)\n        print(\"training done, saving state and generating results\")\n        torch.save(model.state_dict(), model_save_path)\n        print(f\"saving done, model path is {model_save_path}\")\n    elif mode == \"evaluation\":\n        checkpoint_path = (\n            \"../input/lyft-av-py-lightning-resnet-training-baseline/epoch=4.ckpt\"\n        )\n        timestamps, track_ids, coords, confs = evaluation(\n            checkpoint_path,\n            lyft_agent_data_module,\n        )\n        write_pred_csv(\n            \"submission.csv\",\n            timestamps=timestamps,\n            track_ids=track_ids,\n            coords=coords,\n            confs=confs,\n        )\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}