File size: 9,919 Bytes
3133fdb |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Torch Hub Inference Tutorial\n",
"\n",
"In this tutorial you'll learn:\n",
"- how to load a pretrained model using Torch Hub \n",
"- run inference to classify the action in a demo video"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Install and Import modules"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If `torch`, `torchvision` and `pytorchvideo` are not installed, run the following cell:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try:\n",
" import torch\n",
"except ModuleNotFoundError:\n",
" !pip install torch torchvision\n",
" import os\n",
" import sys\n",
" import torch\n",
" \n",
"if torch.__version__=='1.6.0+cu101' and sys.platform.startswith('linux'):\n",
" !pip install pytorchvideo\n",
"else:\n",
" need_pytorchvideo=False\n",
" try:\n",
" # Running notebook locally\n",
" import pytorchvideo\n",
" except ModuleNotFoundError:\n",
" need_pytorchvideo=True\n",
" if need_pytorchvideo:\n",
" # Install from GitHub\n",
" !pip install \"git+https://github.com/facebookresearch/pytorchvideo.git\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import json \n",
"from torchvision.transforms import Compose, Lambda\n",
"from torchvision.transforms._transforms_video import (\n",
" CenterCropVideo,\n",
" NormalizeVideo,\n",
")\n",
"from pytorchvideo.data.encoded_video import EncodedVideo\n",
"from pytorchvideo.transforms import (\n",
" ApplyTransformToKey,\n",
" ShortSideScale,\n",
" UniformTemporalSubsample,\n",
" UniformCropVideo\n",
") \n",
"from typing import Dict"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Setup \n",
"\n",
"Download the id to label mapping for the Kinetics 400 dataset on which the Torch Hub models were trained. \n",
"This will be used to get the category label names from the predicted class ids."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!wget https://dl.fbaipublicfiles.com/pyslowfast/dataset/class_names/kinetics_classnames.json "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"with open(\"kinetics_classnames.json\", \"r\") as f:\n",
" kinetics_classnames = json.load(f)\n",
"\n",
"# Create an id to label name mapping\n",
"kinetics_id_to_classname = {}\n",
"for k, v in kinetics_classnames.items():\n",
" kinetics_id_to_classname[v] = str(k).replace('\"', \"\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Load Model using Torch Hub API\n",
"\n",
"PyTorchVideo provides several pretrained models through Torch Hub. Available models are described in [model zoo documentation](https://github.com/facebookresearch/pytorchvideo/blob/main/docs/source/model_zoo.md#kinetics-400). \n",
"\n",
"Here we are selecting the `slowfast_r50` model which was trained using a 8x8 setting on the Kinetics 400 dataset. \n",
"\n",
"\n",
"NOTE: to run on GPU in Google Colab, in the menu bar selet: Runtime -> Change runtime type -> Harware Accelerator -> GPU\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Device on which to run the model\n",
"# Set to cuda to load on GPU\n",
"device = \"cpu\"\n",
"\n",
"# Pick a pretrained model \n",
"model_name = \"slowfast_r50\"\n",
"model = torch.hub.load(\"facebookresearch/pytorchvideo:main\", model=model_name, pretrained=True)\n",
"\n",
"# Set to eval mode and move to desired device\n",
"model = model.to(device)\n",
"model = model.eval()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Define the transformations for the input required by the model\n",
"\n",
"Before passing the video into the model we need to apply some input transforms and sample a clip of the correct duration.\n",
"\n",
"NOTE: The input transforms are specific to the model. If you choose a different model than the example in this tutorial, please refer to the code provided in the Torch Hub documentation and copy over the relevant transforms:\n",
"- [SlowFast](https://pytorch.org/hub/facebookresearch_pytorchvideo_slowfast/)\n",
"- [X3D](https://pytorch.org/hub/facebookresearch_pytorchvideo_x3d/)\n",
"- [Slow](https://pytorch.org/hub/facebookresearch_pytorchvideo_resnet/)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"####################\n",
"# SlowFast transform\n",
"####################\n",
"\n",
"side_size = 256\n",
"mean = [0.45, 0.45, 0.45]\n",
"std = [0.225, 0.225, 0.225]\n",
"crop_size = 256\n",
"num_frames = 32\n",
"sampling_rate = 2\n",
"frames_per_second = 30\n",
"alpha = 4\n",
"\n",
"class PackPathway(torch.nn.Module):\n",
" \"\"\"\n",
" Transform for converting video frames as a list of tensors. \n",
" \"\"\"\n",
" def __init__(self):\n",
" super().__init__()\n",
" \n",
" def forward(self, frames: torch.Tensor):\n",
" fast_pathway = frames\n",
" # Perform temporal sampling from the fast pathway.\n",
" slow_pathway = torch.index_select(\n",
" frames,\n",
" 1,\n",
" torch.linspace(\n",
" 0, frames.shape[1] - 1, frames.shape[1] // alpha\n",
" ).long(),\n",
" )\n",
" frame_list = [slow_pathway, fast_pathway]\n",
" return frame_list\n",
"\n",
"transform = ApplyTransformToKey(\n",
" key=\"video\",\n",
" transform=Compose(\n",
" [\n",
" UniformTemporalSubsample(num_frames),\n",
" Lambda(lambda x: x/255.0),\n",
" NormalizeVideo(mean, std),\n",
" ShortSideScale(\n",
" size=side_size\n",
" ),\n",
" CenterCropVideo(crop_size),\n",
" PackPathway()\n",
" ]\n",
" ),\n",
")\n",
"\n",
"# The duration of the input clip is also specific to the model.\n",
"clip_duration = (num_frames * sampling_rate)/frames_per_second"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Load an example video\n",
"We can test the classification of an example video from the kinetics validation set such as this [archery video](https://www.youtube.com/watch?v=3and4vWkW4s)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Download the example video file\n",
"!wget https://dl.fbaipublicfiles.com/pytorchvideo/projects/archery.mp4 "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Load the example video\n",
"video_path = \"archery.mp4\" \n",
"\n",
"# Select the duration of the clip to load by specifying the start and end duration\n",
"# The start_sec should correspond to where the action occurs in the video\n",
"start_sec = 0\n",
"end_sec = start_sec + clip_duration \n",
"\n",
"# Initialize an EncodedVideo helper class\n",
"video = EncodedVideo.from_path(video_path)\n",
"\n",
"# Load the desired clip\n",
"video_data = video.get_clip(start_sec=start_sec, end_sec=end_sec)\n",
"\n",
"# Apply a transform to normalize the video input\n",
"video_data = transform(video_data)\n",
"\n",
"# Move the inputs to the desired device\n",
"inputs = video_data[\"video\"]\n",
"inputs = [i.to(device)[None, ...] for i in inputs]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Get model predictions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Pass the input clip through the model \n",
"preds = model(inputs)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Get the predicted classes \n",
"post_act = torch.nn.Softmax(dim=1)\n",
"preds = post_act(preds)\n",
"pred_classes = preds.topk(k=5).indices\n",
"\n",
"# Map the predicted classes to the label names\n",
"pred_class_names = [kinetics_id_to_classname[int(i)] for i in pred_classes[0]]\n",
"print(\"Predicted labels: %s\" % \", \".join(pred_class_names))"
]
}
],
"metadata": {
"bento_stylesheets": {
"bento/extensions/flow/main.css": true,
"bento/extensions/kernel_selector/main.css": true,
"bento/extensions/kernel_ui/main.css": true,
"bento/extensions/new_kernel/main.css": true,
"bento/extensions/system_usage/main.css": true,
"bento/extensions/theme/main.css": true
},
"kernelspec": {
"display_name": "pytorchvideo_etc (local)",
"language": "python",
"name": "pytorchvideo_etc_local"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
|