{"cells":[{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:08:30.007123Z","iopub.status.busy":"2020-10-27T07:08:30.006243Z","iopub.status.idle":"2020-10-27T07:08:35.130068Z","shell.execute_reply":"2020-10-27T07:08:35.128823Z"},"papermill":{"duration":5.164162,"end_time":"2020-10-27T07:08:35.130221","exception":false,"start_time":"2020-10-27T07:08:29.966059","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"# common imports\nimport os\nimport numpy as np\nfrom tqdm import tqdm\nimport random\nimport time\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom pathlib import Path\nfrom tempfile import gettempdir\nfrom typing import Dict\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# torch imports\nimport torch\nfrom torch import nn, optim\nfrom torch.utils.data import DataLoader, SubsetRandomSampler\nfrom torchvision.models.resnet import resnet50, resnet18, resnet34, resnet101\nimport torch.nn.functional as F\n\n\n# l5kit imports\nimport l5kit\nfrom l5kit.configs import load_config_data\nfrom l5kit.data import LocalDataManager, ChunkedDataset\nfrom l5kit.dataset import AgentDataset, EgoDataset\nfrom l5kit.rasterization import build_rasterizer\nfrom l5kit.evaluation import write_pred_csv, compute_metrics_csv, read_gt_csv, create_chopped_dataset\nfrom l5kit.evaluation.chop_dataset import MIN_FUTURE_STEPS\nfrom l5kit.evaluation.metrics import neg_multi_log_likelihood, time_displace\nfrom l5kit.geometry import transform_points\nfrom l5kit.visualization import PREDICTED_POINTS_COLOR, TARGET_POINTS_COLOR, draw_trajectory\nfrom prettytable import PrettyTable\nfrom pathlib import Path","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:08:35.191321Z","iopub.status.busy":"2020-10-27T07:08:35.190176Z","iopub.status.idle":"2020-10-27T07:08:35.194924Z","shell.execute_reply":"2020-10-27T07:08:35.195499Z"},"papermill":{"duration":0.039257,"end_time":"2020-10-27T07:08:35.195647","exception":false,"start_time":"2020-10-27T07:08:35.15639","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"l5kit.__version__","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:08:35.619047Z","iopub.status.busy":"2020-10-27T07:08:35.618262Z","iopub.status.idle":"2020-10-27T07:08:35.626209Z","shell.execute_reply":"2020-10-27T07:08:35.625648Z"},"papermill":{"duration":0.404212,"end_time":"2020-10-27T07:08:35.62633","exception":false,"start_time":"2020-10-27T07:08:35.222118","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"torch.cuda.is_available()","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:08:35.686774Z","iopub.status.busy":"2020-10-27T07:08:35.686087Z","iopub.status.idle":"2020-10-27T07:08:35.690318Z","shell.execute_reply":"2020-10-27T07:08:35.690822Z"},"papermill":{"duration":0.036933,"end_time":"2020-10-27T07:08:35.691023","exception":false,"start_time":"2020-10-27T07:08:35.65409","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"def find_no_of_trainable_params(model):\n    total_trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n    #print(total_trainable_params)\n    return total_trainable_params","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:08:35.751967Z","iopub.status.busy":"2020-10-27T07:08:35.751154Z","iopub.status.idle":"2020-10-27T07:08:35.758437Z","shell.execute_reply":"2020-10-27T07:08:35.757764Z"},"papermill":{"duration":0.040613,"end_time":"2020-10-27T07:08:35.758561","exception":false,"start_time":"2020-10-27T07:08:35.717948","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"def set_seed(seed):\n    random.seed(seed)\n    np.random.seed(seed)\n    os.environ[\"PYTHONHASHSEED\"] = str(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    \nset_seed(42)","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:08:35.818579Z","iopub.status.busy":"2020-10-27T07:08:35.817685Z","iopub.status.idle":"2020-10-27T07:08:35.822405Z","shell.execute_reply":"2020-10-27T07:08:35.821766Z"},"papermill":{"duration":0.036343,"end_time":"2020-10-27T07:08:35.822544","exception":false,"start_time":"2020-10-27T07:08:35.786201","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"#!rm /kaggle/working/*","execution_count":null,"outputs":[]},{"metadata":{"papermill":{"duration":0.027167,"end_time":"2020-10-27T07:08:35.877164","exception":false,"start_time":"2020-10-27T07:08:35.849997","status":"completed"},"tags":[]},"cell_type":"markdown","source":"## Configs"},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:08:35.954307Z","iopub.status.busy":"2020-10-27T07:08:35.949367Z","iopub.status.idle":"2020-10-27T07:08:35.957189Z","shell.execute_reply":"2020-10-27T07:08:35.956602Z"},"papermill":{"duration":0.049453,"end_time":"2020-10-27T07:08:35.957318","exception":false,"start_time":"2020-10-27T07:08:35.907865","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"# --- Lyft configs ---\ncfg = {\n    'format_version': 4,\n    'data_path': \"../input/lyft-motion-prediction-autonomous-vehicles/\",\n    'model_params': {\n        'model_architecture': 'resnet34',\n        'history_num_frames': 10,\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        'model_name': \"R34_pvt_10_224_norm_agent_features_nll_multimode_ReducedLR\",\n        'lr': 7e-4,\n        'weight_path': \"../input/lyft-motion-prediction-resnet-weight-files/R34_pvt_10_224_norm_agent_features_nll_multimode_ReduceLr_1752k.pth\",\n        'train': True,\n        'predict': False\n    },\n\n    'raster_params': {\n        'raster_size': [224, 224],\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    },\n\n    'train_data_loader': {\n        'key': 'scenes/train.zarr',\n        'batch_size': 32,\n        'shuffle': True,\n        'num_workers': 4\n    },\n    \n    'val_data_loader': {\n        'key': 'scenes/validate.zarr',\n        'batch_size': 16,\n        'shuffle': True,\n        'num_workers': 4\n    },\n    \n    'test_data_loader': {\n        'key': 'scenes/test.zarr',\n        'batch_size': 32,\n        'shuffle': False,\n        'num_workers': 4\n    },\n\n    'train_params': {\n        'train_start_index' : 54751,\n        'max_num_steps': 8000,\n        'checkpoint_every_n_steps': 250,\n    }\n}","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:08:36.029079Z","iopub.status.busy":"2020-10-27T07:08:36.028179Z","iopub.status.idle":"2020-10-27T07:08:36.030808Z","shell.execute_reply":"2020-10-27T07:08:36.03135Z"},"papermill":{"duration":0.043984,"end_time":"2020-10-27T07:08:36.031559","exception":false,"start_time":"2020-10-27T07:08:35.987575","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"NUMBER_OF_HISTORY_FRAMES = cfg['model_params']['history_num_frames'] + 1\nRASTER_IMG_SIZE = cfg['raster_params']['raster_size'][0]\nNUM_MODES = 3\nNUMBER_OF_FUTURE_FRAMES = cfg['model_params']['future_num_frames']\nTRAIN_BATCH_SIZE = cfg['train_data_loader']['batch_size'] \n### TRAIN FROM WHERE LEFT OFF, CHANGE THE STARTING INDICES VARIABLE ACCORDINGLY\nTRAIN_START_INDICES = cfg['train_params']['train_start_index']\nEXTENT_RANGE = 5.0 ","execution_count":null,"outputs":[]},{"metadata":{"papermill":{"duration":0.028581,"end_time":"2020-10-27T07:08:36.090344","exception":false,"start_time":"2020-10-27T07:08:36.061763","status":"completed"},"tags":[]},"cell_type":"markdown","source":"## Load the train and test data"},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:08:36.156967Z","iopub.status.busy":"2020-10-27T07:08:36.155378Z","iopub.status.idle":"2020-10-27T07:08:36.157996Z","shell.execute_reply":"2020-10-27T07:08:36.158726Z"},"papermill":{"duration":0.038812,"end_time":"2020-10-27T07:08:36.158931","exception":false,"start_time":"2020-10-27T07:08:36.120119","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"# set env variable for data\nDIR_INPUT = cfg[\"data_path\"]\nos.environ[\"L5KIT_DATA_FOLDER\"] = DIR_INPUT\ndm = LocalDataManager(None)\nrasterizer = build_rasterizer(cfg, dm)","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:08:36.222728Z","iopub.status.busy":"2020-10-27T07:08:36.22174Z","iopub.status.idle":"2020-10-27T07:09:34.830441Z","shell.execute_reply":"2020-10-27T07:09:34.829105Z"},"papermill":{"duration":58.643127,"end_time":"2020-10-27T07:09:34.830602","exception":false,"start_time":"2020-10-27T07:08:36.187475","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"# ===== INIT TRAIN DATASET============================================================\ntrain_cfg = cfg[\"train_data_loader\"]\ntrain_zarr = ChunkedDataset(dm.require(train_cfg[\"key\"])).open()\ntrain_dataset = AgentDataset(cfg, train_zarr, rasterizer)","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:09:34.893453Z","iopub.status.busy":"2020-10-27T07:09:34.892683Z","iopub.status.idle":"2020-10-27T07:09:34.904305Z","shell.execute_reply":"2020-10-27T07:09:34.905008Z"},"papermill":{"duration":0.046285,"end_time":"2020-10-27T07:09:34.905164","exception":false,"start_time":"2020-10-27T07:09:34.858879","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"print('Length of Train dataset is ' ,len(train_dataset))\nprint(\"==================================TRAIN DATA==================================\")\nprint(train_dataset)","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:09:34.971271Z","iopub.status.busy":"2020-10-27T07:09:34.969832Z","iopub.status.idle":"2020-10-27T07:09:36.072316Z","shell.execute_reply":"2020-10-27T07:09:36.071508Z"},"papermill":{"duration":1.138428,"end_time":"2020-10-27T07:09:36.072488","exception":false,"start_time":"2020-10-27T07:09:34.93406","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"sampled_indices = np.random.choice(len(train_dataset), size = len(train_dataset), replace = False)\nprint('Before slicing, start indices are ', sampled_indices[0:10])","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:09:36.134741Z","iopub.status.busy":"2020-10-27T07:09:36.134063Z","iopub.status.idle":"2020-10-27T07:09:36.139861Z","shell.execute_reply":"2020-10-27T07:09:36.140448Z"},"papermill":{"duration":0.039209,"end_time":"2020-10-27T07:09:36.140604","exception":false,"start_time":"2020-10-27T07:09:36.101395","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"TRAIN_START_INDICES","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:09:36.20489Z","iopub.status.busy":"2020-10-27T07:09:36.2041Z","iopub.status.idle":"2020-10-27T07:09:36.209725Z","shell.execute_reply":"2020-10-27T07:09:36.210516Z"},"papermill":{"duration":0.040102,"end_time":"2020-10-27T07:09:36.210682","exception":false,"start_time":"2020-10-27T07:09:36.17058","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"sampled_indices = sampled_indices[TRAIN_START_INDICES:]\nprint('After slicing, start indices are ', sampled_indices[0:10])","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:09:36.275147Z","iopub.status.busy":"2020-10-27T07:09:36.274417Z","iopub.status.idle":"2020-10-27T07:09:36.279089Z","shell.execute_reply":"2020-10-27T07:09:36.278496Z"},"papermill":{"duration":0.03795,"end_time":"2020-10-27T07:09:36.279218","exception":false,"start_time":"2020-10-27T07:09:36.241268","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"Datasampler = SubsetRandomSampler(sampled_indices)","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:09:36.343672Z","iopub.status.busy":"2020-10-27T07:09:36.342877Z","iopub.status.idle":"2020-10-27T07:09:36.346255Z","shell.execute_reply":"2020-10-27T07:09:36.346825Z"},"papermill":{"duration":0.038115,"end_time":"2020-10-27T07:09:36.34697","exception":false,"start_time":"2020-10-27T07:09:36.308855","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"train_dataloader = DataLoader(train_dataset, sampler=Datasampler, batch_size=train_cfg[\"batch_size\"], \n                             num_workers=train_cfg[\"num_workers\"])","execution_count":null,"outputs":[]},{"metadata":{"papermill":{"duration":0.029955,"end_time":"2020-10-27T07:09:36.407814","exception":false,"start_time":"2020-10-27T07:09:36.377859","status":"completed"},"tags":[]},"cell_type":"markdown","source":"## Loss function"},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:09:36.48951Z","iopub.status.busy":"2020-10-27T07:09:36.475721Z","iopub.status.idle":"2020-10-27T07:09:36.492632Z","shell.execute_reply":"2020-10-27T07:09:36.492053Z"},"papermill":{"duration":0.055305,"end_time":"2020-10-27T07:09:36.492737","exception":false,"start_time":"2020-10-27T07:09:36.437432","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"# --- Function utils ---\n# Original code from https://github.com/lyft/l5kit/blob/20ab033c01610d711c3d36e1963ecec86e8b85b6/l5kit/l5kit/evaluation/metrics.py\nfrom torch import Tensor\n\n\ndef pytorch_neg_multi_log_likelihood_batch(\n    gt: Tensor, pred: Tensor, confidences: Tensor, 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 == (batch_size, future_len, num_coords), f\"expected 2D (Time x Coords) array for gt, got {gt.shape}\"\n    assert confidences.shape == (batch_size, num_modes), f\"expected 1D (Modes) array for gt, got {confidences.shape}\"\n    assert torch.allclose(torch.sum(confidences, dim=1), confidences.new_ones((batch_size,))), \"confidences should sum to 1\"\n    assert avails.shape == (batch_size, future_len), f\"expected 1D (Time) array for gt, 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(((gt - pred) * avails) ** 2, dim=-1)  # reduce coords and use availability\n\n    with np.errstate(divide=\"ignore\"):  # 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(dim=1, keepdim=True)  # error are negative at this point, so max() gives the minimum one\n    error = -torch.log(torch.sum(torch.exp(error - max_value), dim=-1, keepdim=True)) - max_value  # reduce modes\n    # print(\"error\", error)\n    return torch.mean(error)\n\n\ndef pytorch_neg_multi_log_likelihood_single(\n    gt: Tensor, pred: Tensor, avails: Tensor\n) -> Tensor:\n    \"\"\"\n\n    Args:\n        gt (Tensor): array of shape (bs)x(time)x(2D coords)\n        pred (Tensor): array of shape (bs)x(time)x(2D coords)\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    # pred (bs)x(time)x(2D coords) --> (bs)x(mode=1)x(time)x(2D coords)\n    # create confidence (bs)x(mode=1)\n    batch_size, future_len, num_coords = pred.shape\n    confidences = pred.new_ones((batch_size, 1))\n    return pytorch_neg_multi_log_likelihood_batch(gt, pred.unsqueeze(1), confidences, avails)","execution_count":null,"outputs":[]},{"metadata":{"papermill":{"duration":0.029697,"end_time":"2020-10-27T07:09:36.552889","exception":false,"start_time":"2020-10-27T07:09:36.523192","status":"completed"},"tags":[]},"cell_type":"markdown","source":"## Model"},{"metadata":{"papermill":{"duration":0.030105,"end_time":"2020-10-27T07:09:36.613338","exception":false,"start_time":"2020-10-27T07:09:36.583233","status":"completed"},"tags":[]},"cell_type":"markdown","source":"Next we define the baseline model. Note that this model will return three possible trajectories together with confidence score for each trajectory."},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:09:36.698477Z","iopub.status.busy":"2020-10-27T07:09:36.694273Z","iopub.status.idle":"2020-10-27T07:09:36.70145Z","shell.execute_reply":"2020-10-27T07:09:36.70087Z"},"papermill":{"duration":0.057549,"end_time":"2020-10-27T07:09:36.701569","exception":false,"start_time":"2020-10-27T07:09:36.64402","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"class LyftMultiModel(nn.Module):\n\n    def __init__(self, cfg: Dict, num_modes=3):\n        super().__init__()\n\n        architecture = cfg[\"model_params\"][\"model_architecture\"]\n        backbone = eval(architecture)(pretrained=True)\n        self.backbone = backbone\n\n        num_history_channels = (cfg[\"model_params\"][\"history_num_frames\"] + 1) * 2\n        num_in_channels = 3 + num_history_channels\n\n        self.backbone.conv1 = nn.Conv2d(\n            num_in_channels,\n            self.backbone.conv1.out_channels,\n            kernel_size=self.backbone.conv1.kernel_size,\n            stride=self.backbone.conv1.stride,\n            padding=self.backbone.conv1.padding,\n            bias=False,\n        )\n\n        # This is 512 for resnet18 and resnet34;\n        # And it is 2048 for the other resnets\n        \n        if architecture == \"resnet50\":\n            backbone_out_features = 2048\n        else:\n            backbone_out_features = 512\n\n        self.dropout = nn.Dropout(p=0.3)\n            \n        # X, Y coords for the future positions (output shape: batch_sizex50x2)\n        self.future_len = cfg[\"model_params\"][\"future_num_frames\"]\n        num_targets = 2 * self.future_len\n        other_agent_features = num_history_channels + 3 # extent info is 3d \n        total_num_features = backbone_out_features + other_agent_features\n        self.head = nn.Linear(in_features=total_num_features, out_features=1024)\n\n        # final prediction - a fc layer with desired number of outputs, no activation\n        self.num_preds = num_targets * num_modes\n        self.num_modes = num_modes\n        self.logit = nn.Linear(1024, out_features=self.num_preds + num_modes)\n\n    def forward(self, x, agent_data):\n        x = self.backbone.conv1(x)\n        x = self.backbone.bn1(x)\n        x = self.backbone.relu(x)\n        x = self.backbone.maxpool(x)\n\n        x = self.backbone.layer1(x)\n        x = self.backbone.layer2(x)\n        x = self.backbone.layer3(x)\n        x = self.backbone.layer4(x)\n\n        x = self.backbone.avgpool(x)\n        x = torch.flatten(x, 1)\n        \n        # adding other agent data to image data\n        x = torch.cat((x, agent_data), dim=1)\n\n        # fc with relu activation and dropout\n        x = self.dropout(F.relu(self.head(x)))\n        x = self.logit(x)\n\n        # pred (batch_size)x(modes)x(time)x(2D coords)\n        # confidences (batch_size)x(modes)\n        bs, _ = x.shape\n        pred, confidences = torch.split(x, self.num_preds, dim=1)\n        pred = pred.view(bs, self.num_modes, self.future_len, 2)\n        assert confidences.shape == (bs, self.num_modes)\n        confidences = torch.softmax(confidences, dim=1)\n        return pred, confidences","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:09:36.772689Z","iopub.status.busy":"2020-10-27T07:09:36.770861Z","iopub.status.idle":"2020-10-27T07:09:36.77347Z","shell.execute_reply":"2020-10-27T07:09:36.774028Z"},"papermill":{"duration":0.042106,"end_time":"2020-10-27T07:09:36.774166","exception":false,"start_time":"2020-10-27T07:09:36.73206","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"def forward(data, model, device, criterion = pytorch_neg_multi_log_likelihood_batch):\n    inputs = data[\"image\"].to(device)\n    target_availabilities = data[\"target_availabilities\"].to(device)\n    targets = data[\"target_positions\"].to(device)\n    bs = inputs.shape[0]\n    history_positions = data['history_positions'].to(device).view(bs, -1)\n    # centroid = data['centroid'].to(device).float()\n    # yaw = data['yaw'].to(device).view(TRAIN_BATCH_SIZE, 1).float()\n    # agent_data = torch.cat((history_positions, centroid, yaw, extent), dim=1)\n    extent = data['extent'].to(device) / EXTENT_RANGE\n    agent_data = torch.cat((history_positions, extent), dim=1)\n    \n    # Forward pass\n    preds, confidences = model(inputs, agent_data)\n    loss = criterion(targets, preds, confidences, target_availabilities)\n    return loss, preds, confidences","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:09:36.844144Z","iopub.status.busy":"2020-10-27T07:09:36.84332Z","iopub.status.idle":"2020-10-27T07:09:36.848285Z","shell.execute_reply":"2020-10-27T07:09:36.849038Z"},"papermill":{"duration":0.044074,"end_time":"2020-10-27T07:09:36.849227","exception":false,"start_time":"2020-10-27T07:09:36.805153","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"# ==== INIT MODEL=================\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nprint(f'device {device}')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Model, optimizer, Learning rate schedulers"},{"metadata":{"trusted":true},"cell_type":"code","source":"## Learning rate scheudler params\n## https://pytorch.org/docs/stable/optim.html#torch.optim.lr_scheduler.ReduceLROnPlateau\nred_factor = 0.8\npatience_steps = 1000 \npatience_threshold = 0.1 \nsmoothing = 0.02","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:09:36.918821Z","iopub.status.busy":"2020-10-27T07:09:36.918056Z","iopub.status.idle":"2020-10-27T07:09:39.689549Z","shell.execute_reply":"2020-10-27T07:09:39.688282Z"},"papermill":{"duration":2.808493,"end_time":"2020-10-27T07:09:39.689735","exception":false,"start_time":"2020-10-27T07:09:36.881242","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"model = LyftMultiModel(cfg)\nmodel.to(device)\noptimizer = optim.Adam(model.parameters(), lr=cfg[\"model_params\"][\"lr\"])\nscheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', factor=red_factor, \n                                                 patience=patience_steps, threshold= patience_threshold,\n                                                verbose= True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"optimizer.state_dict()[\"param_groups\"][0][\"lr\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# load weight if there is a pretrained model\nweight_path = cfg[\"model_params\"][\"weight_path\"]\nif weight_path != '':\n    checkpoint = torch.load(weight_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.load_state_dict(checkpoint['state_dict'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"optimizer.load_state_dict(checkpoint['optimizer'])\nfor param_group in optimizer.param_groups:\n    param_group['lr'] = cfg[\"model_params\"][\"lr\"] ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"optimizer.state_dict()[\"param_groups\"][0][\"lr\"]","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:09:44.771635Z","iopub.status.busy":"2020-10-27T07:09:44.770448Z","iopub.status.idle":"2020-10-27T07:09:44.774786Z","shell.execute_reply":"2020-10-27T07:09:44.77536Z"},"papermill":{"duration":0.046499,"end_time":"2020-10-27T07:09:44.775514","exception":false,"start_time":"2020-10-27T07:09:44.729015","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"find_no_of_trainable_params(model)","execution_count":null,"outputs":[]},{"metadata":{"papermill":{"duration":0.034764,"end_time":"2020-10-27T07:09:44.845216","exception":false,"start_time":"2020-10-27T07:09:44.810452","status":"completed"},"tags":[]},"cell_type":"markdown","source":"## Training loop"},{"metadata":{"papermill":{"duration":0.034665,"end_time":"2020-10-27T07:09:44.915016","exception":false,"start_time":"2020-10-27T07:09:44.880351","status":"completed"},"tags":[]},"cell_type":"markdown","source":"Next let us implement the training loop, when the **train** parameter is set to True. "},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:09:44.990549Z","iopub.status.busy":"2020-10-27T07:09:44.989622Z","iopub.status.idle":"2020-10-27T07:09:44.993307Z","shell.execute_reply":"2020-10-27T07:09:44.993856Z"},"papermill":{"duration":0.044278,"end_time":"2020-10-27T07:09:44.994025","exception":false,"start_time":"2020-10-27T07:09:44.949747","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"TRAIN_START_INDICES","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:09:45.071549Z","iopub.status.busy":"2020-10-27T07:09:45.07061Z","iopub.status.idle":"2020-10-27T07:09:45.075259Z","shell.execute_reply":"2020-10-27T07:09:45.075832Z"},"papermill":{"duration":0.04626,"end_time":"2020-10-27T07:09:45.076005","exception":false,"start_time":"2020-10-27T07:09:45.029745","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"print('TRAINING ABOUT TO START ... FROM ', TRAIN_START_INDICES, \n      '  BATCH AND FOR ', cfg['train_params']['max_num_steps'], ' BATCHES', ' WITH BATCH SIZE', TRAIN_BATCH_SIZE)","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-10-27T07:09:45.169773Z","iopub.status.busy":"2020-10-27T07:09:45.162344Z","iopub.status.idle":"2020-10-27T13:44:42.361671Z","shell.execute_reply":"2020-10-27T13:44:42.367019Z"},"papermill":{"duration":23697.255193,"end_time":"2020-10-27T13:44:42.367407","exception":false,"start_time":"2020-10-27T07:09:45.112214","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"# ==== TRAINING LOOP =========================================================\nif cfg[\"model_params\"][\"train\"]:\n    \n    tr_it = iter(train_dataloader)\n    progress_bar = tqdm(range(TRAIN_START_INDICES, \n                              TRAIN_START_INDICES + cfg[\"train_params\"][\"max_num_steps\"]))\n    num_iter = cfg[\"train_params\"][\"max_num_steps\"]\n    losses_train = []\n    smooth_losses = []\n    lr_list = []\n    iterations = []\n    metrics = []\n    times = []\n    model_name = cfg[\"model_params\"][\"model_name\"]\n    start = time.time()\n    iteration = 0\n    \n    for i in progress_bar:\n        try:\n            data = next(tr_it)\n        except StopIteration:\n            tr_it = iter(train_dataloader)\n            data = next(tr_it)\n        \n        # Forward pass\n        model.train()\n        torch.set_grad_enabled(True)\n        loss, _, _ = forward(data, model, device)\n\n        # Backward pass\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n        losses_train.append(loss.item())\n\n        progress_bar.set_description(f\"loss: {loss.item()} loss(avg): {np.mean(losses_train)}\")\n        if i % cfg['train_params']['checkpoint_every_n_steps'] == 0:\n            sample_number = i * cfg['train_data_loader']['batch_size']            \n            state = {\n              'state_dict': model.state_dict(),\n              'optimizer': optimizer.state_dict(),\n              'scheduler' : scheduler\n            }\n            torch.save(state, f'{model_name}_{sample_number}k.pth')\n            iterations.append(i)\n            metrics.append(np.mean(losses_train))\n            times.append((time.time()-start)/60)\n            \n        # smooth the loss\n        if i== TRAIN_START_INDICES:\n            smooth_losses.append(loss.item())\n        else:\n            smooth_losses.append(smoothing  * loss.item() + (1 - smoothing) * smooth_losses[-1])\n    \n        scheduler.step(smooth_losses[-1])\n        lr_list.append(optimizer.state_dict()[\"param_groups\"][0][\"lr\"])\n\n    sample_number = i * cfg['train_data_loader']['batch_size']\n    results = pd.DataFrame({'iterations': iterations, 'metrics (avg)': metrics, 'elapsed_time (mins)': times})\n    results.to_csv(f\"train_metrics_{model_name}_{sample_number}k.csv\", index = False)\n    train_losses_csv = pd.DataFrame({'iteration': TRAIN_START_INDICES + np.arange(len(losses_train)), \n                                 'losses_train': losses_train,\n                                 'smooth_losses': smooth_losses, \n                                    'learning_rate' : lr_list})\n    train_losses_csv.to_csv(f\"train_losses_{model_name}_{sample_number}k.csv\", index = False)\n    print(f\"Total training time is {(time.time()-start)/60} mins\")\n    print(results.head())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_raw_vs_smooth_loss(raw_loss, smooth_losses, start_idx =0, end_idx = None):\n    if end_idx is None:\n        end_idx = len(raw_loss)\n    plt.figure(figsize=(8, 8))\n    plt.plot(range(start_idx,end_idx), raw_loss[start_idx:end_idx], label = 'raw_loss');\n    plt.plot(range(start_idx,end_idx), smooth_losses[start_idx:end_idx], label = 'smoothened loss');\n    plt.xlabel('Training_steps')\n    plt.ylabel('Train_losses')\n    plt.grid(True)\n    plt.legend()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_raw_vs_smooth_loss(losses_train, smooth_losses)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Evaluation"},{"metadata":{"trusted":true},"cell_type":"code","source":"def model_validation_score(model, pred_path):\n    # ==== EVAL LOOP\n    model.eval()\n    torch.set_grad_enabled(False)\n\n    # store information for evaluation\n    future_coords_offsets_pd = []\n    timestamps = []\n    confidences_list = []\n    agent_ids = []\n    progress_bar = tqdm(eval_dataloader)\n\n    for data in progress_bar:\n\n        _, preds, confidences = forward(data, model, device)\n\n        #fix for the new environment\n        preds = preds.cpu().numpy()\n        world_from_agents = data[\"world_from_agent\"].numpy()\n        centroids = data[\"centroid\"].numpy()\n        coords_offset = []\n\n        # convert into world coordinates and compute offsets\n        for idx in range(len(preds)):\n            for mode in range(3):\n                preds[idx, mode, :, :] = transform_points(preds[idx, mode, :, :], world_from_agents[idx]) - centroids[idx][:2]\n\n        future_coords_offsets_pd.append(preds.copy())\n        confidences_list.append(confidences.cpu().numpy().copy())\n        timestamps.append(data[\"timestamp\"].numpy().copy())\n        agent_ids.append(data[\"track_id\"].numpy().copy())  \n    \n    write_pred_csv(pred_path,\n               timestamps=np.concatenate(timestamps),\n               track_ids=np.concatenate(agent_ids),\n               coords=np.concatenate(future_coords_offsets_pd),\n               confs=np.concatenate(confidences_list),\n              )\n    \n    metrics = compute_metrics_csv(eval_gt_path, pred_path, [neg_multi_log_likelihood, time_displace])\n    for metric_name, metric_mean in metrics.items():\n        print(metric_name, metric_mean)\n        np.save(metric_name + '.npy', metric_mean)\n        np.savetxt(metric_name + '.csv', metric_mean, delimiter=',')\n    #return [future_coords_offsets_pd, confidences_list, timestamps, agent_ids]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"run_validation = False\n\nif run_validation == True:\n    eval_base_path = \"../input/lyft-validation-chopped-100/validate_chopped_100\"\n    eval_cfg = cfg[\"val_data_loader\"]\n    eval_zarr_path = str(Path(eval_base_path) / Path(dm.require(eval_cfg[\"key\"])).name)\n    eval_mask_path = str(Path(eval_base_path) / \"mask.npz\")\n    eval_gt_path = str(Path(eval_base_path) / \"gt.csv\")\n\n    eval_zarr = ChunkedDataset(eval_zarr_path).open()\n    eval_mask = np.load(eval_mask_path)[\"arr_0\"]\n    # ===== INIT DATASET AND LOAD MASK\n    eval_dataset = AgentDataset(cfg, eval_zarr, rasterizer, agents_mask=eval_mask)\n    eval_dataloader = DataLoader(eval_dataset, shuffle=eval_cfg[\"shuffle\"], batch_size=eval_cfg[\"batch_size\"], \n                                 num_workers=eval_cfg[\"num_workers\"])\n    print(eval_dataset)\n    \n    pred_path = f\"{gettempdir()}/pred.csv\"\n    model_validation_score(model, pred_path)\n    ","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}