Skip to content

Commit

Permalink
v0.2.71
Browse files Browse the repository at this point in the history
  • Loading branch information
kory committed Feb 22, 2024
1 parent aeb47d9 commit 6dc1348
Show file tree
Hide file tree
Showing 863 changed files with 59,333 additions and 30 deletions.
11 changes: 11 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Copyright 2024 Qualcomm® Technologies, Inc.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
403 changes: 373 additions & 30 deletions README.md

Large diffs are not rendered by default.

78 changes: 78 additions & 0 deletions mypy.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
[mypy]
# https://mypy.readthedocs.io/en/stable/config_file.html#import-discovery
exclude = "qai_hub_models/models"

[mypy-huggingface_hub.*]
ignore_missing_imports = True

[mypy-onnx.*]
ignore_missing_imports = True

[mypy-onnxsim.*]
ignore_missing_imports = True

[mypy-onnxruntime.*]
ignore_missing_imports = True

[mypy-pytimeparse.*]
ignore_missing_imports = True

[mypy-skimage.*]
ignore_missing_imports = True

[mypy-setuptools.*]
ignore_missing_imports = True

[mypy-tensorflow.*]
ignore_missing_imports = True

[mypy-torchvision.*]
ignore_missing_imports = True

[mypy-transformers.*]
ignore_missing_imports = True

[mypy-tqdm.*]
ignore_missing_imports = True

[mypy-tap.*]
ignore_missing_imports = True

[mypy-h5py.*]
ignore_missing_imports = True

[mypy-flatbuffers.*]
ignore_missing_imports = True

[mypy-soundfile.*]
ignore_missing_imports = True

[mypy-datasets.*]
ignore_missing_imports = True

[mypy-keras.*]
ignore_missing_imports = True

[mypy-rangefilter.filters.*]
ignore_missing_imports = True

[mypy-schema.*]
ignore_missing_imports = True

[mypy-gdown.*]
ignore_missing_imports = True

[mypy-aimet_torch.*]
ignore_missing_imports = True

[mypy-boto3.*]
ignore_missing_imports = True

[mypy-botocore.*]
ignore_missing_imports = True

[mypy-ruamel.*]
ignore_missing_imports = True

[mypy-qai_hub_models.models.*]
ignore_errors = true
26 changes: 26 additions & 0 deletions pyrightconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"exclude": [
"**/.mypy_cache",
"**/.pytest_cache",
"**/__pycache__",
"**/node_modules",
"build/tungsten",
"src/public/staging_python/qai_hub_staging",
"src/tungsten",
"src/www/onnx-optimizer/third_party",
"src/www/onnx-simplifier/third_party",
],

"extraPaths": [
"./build/proto"
],

"reportMissingModuleSource": "none",
"reportMissingImports": true,
"reportMissingTypeStubs": false,
"reportShadowedImports": false,
"verboseOutput": false,

"venvPath": ".",
"venv": "qaism-dev"
}
16 changes: 16 additions & 0 deletions pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[pytest]
testpaths = qai_hub_models
norecursedirs = build
python_files = tests.py test_*.py test.py
filterwarnings =
ignore::DeprecationWarning:coremltools.*:
ignore::DeprecationWarning:torch.*:
ignore::DeprecationWarning:torchvision.*:
ignore::DeprecationWarning:tensorflow.*:
ignore::DeprecationWarning:tensorflow-macos.*:
ignore::DeprecationWarning:tensorflow-metal.*:
ignore::DeprecationWarning:tensorflow-probability.*:
markers =
serial: test must not be run in parallel
slow: marks tests as slow
slow_cloud: marks test as slow and cloud-dependent
Empty file added qai_hub_models/__init__.py
Empty file.
1 change: 1 addition & 0 deletions qai_hub_models/_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__version__ = "0.2.71"
12 changes: 12 additions & 0 deletions qai_hub_models/asset_bases.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
store_url: https://qaihub-public-assets.s3.us-west-2.amazonaws.com/qai-hub-models
web_asset_folder: models/{model_id}/web-assets
static_web_banner_filename: banner.png
animated_web_banner_filename: banner.mp4
model_asset_folder: models/{model_id}/v{version}
dataset_asset_folder: datasets/{dataset_id}/v{version}
repo_url: https://github.com/quic/ai-hub-models/blob/main
qaihm_repo: qai_hub_models/models/{model_id}
example_use: qai_hub_models/models/{model_id}#example--usage
huggingface_path: qualcomm/{model_name}
models_website_url: https://aihub.qualcomm.com
models_website_relative_path: models/{model_id}
4 changes: 4 additions & 0 deletions qai_hub_models/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
def pytest_configure(config):
config.addinivalue_line("markers", "compile: Run compile tests.")
config.addinivalue_line("markers", "profile: Run profile tests.")
config.addinivalue_line("markers", "inference: Run inference tests.")
Empty file.
124 changes: 124 additions & 0 deletions qai_hub_models/datasets/bsd300.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
from __future__ import annotations

import os
from typing import Tuple

import numpy as np
import torch
from PIL import Image

from qai_hub_models.datasets.common import BaseDataset
from qai_hub_models.utils.asset_loaders import CachedWebDatasetAsset

BSD300_URL = (
"https://www2.eecs.berkeley.edu/Research/Projects/CS/vision/bsds/BSDS300-images.tgz"
)
BSD300_FOLDER_NAME = "BSDS300"
BSD300_VERSION = 1
BSD300_ASSET = CachedWebDatasetAsset(
BSD300_URL, BSD300_FOLDER_NAME, BSD300_VERSION, "BSDS300.tgz"
)
DATASET_LENGTH = 200


class BSD300Dataset(BaseDataset):
"""
BSD300 published here: https://www2.eecs.berkeley.edu/Research/Projects/CS/vision/bsds/
"""

def __init__(self, scaling_factor=4):
self.bsd_path = BSD300_ASSET.path(extracted=True)
self.images_path = os.path.join(self.bsd_path, "images/train")
BaseDataset.__init__(self, self.bsd_path)
self.scaling_factor = scaling_factor

def _validate_data(self) -> bool:
images_path = os.path.join(self.dataset_path, "images/train")

# Check image path exists
if not os.path.exists(images_path):
return False

# Ensure the correct number of images are there
files = os.listdir(images_path)
images = [f for f in files if ".jpg" in f]
if len(images) != DATASET_LENGTH:
return False

return True

def _prepare_data(self):
# Rename images to be more friendly to enumeration
directory = os.path.join(self.dataset_path, "images/train")
files = os.listdir(directory)
for i, filename in enumerate(files):
if filename.endswith(".jpg"):
# Open the image and convert it to png
try:
with Image.open(os.path.join(directory, filename)) as img:
img.save(os.path.join(directory, f"img_{i + 1:03d}_HR.jpg"))
# delete the old image
os.remove(os.path.join(directory, filename))
except ValueError:
print(f"File {filename} does not exist!")

def __len__(self):
return DATASET_LENGTH

def __getitem__(self, item) -> Tuple[torch.Tensor, torch.Tensor]:
# We use the super resolution GT-and-test image preparation from AIMET zoo:
# https://github.com/quic/aimet-model-zoo/blob/d09d2b0404d10f71a7640a87e9d5e5257b028802/aimet_zoo_torch/quicksrnet/dataloader/utils.py#L51

img = np.asarray(
Image.open(os.path.join(self.images_path, f"img_{item + 1:03d}_HR.jpg"))
)
height, width = img.shape[0:2]

# If portrait, transpose to landscape so that all tensors are equal size
if height > width:
img = np.transpose(img, (1, 0, 2))
height, width = img.shape[0:2]

# Take the largest possible center-crop of it such that its dimensions are perfectly divisible by the scaling factor
x_remainder = width % (
2 * self.scaling_factor
if self.scaling_factor == 1.5
else self.scaling_factor
)
y_remainder = height % (
2 * self.scaling_factor
if self.scaling_factor == 1.5
else self.scaling_factor
)
left = int(x_remainder // 2)
top = int(y_remainder // 2)
right = int(left + (width - x_remainder))
bottom = int(top + (height - y_remainder))
hr_img = img[top:bottom, left:right]

hr_height, hr_width = hr_img.shape[0:2]

hr_img = np.array(hr_img, dtype="uint8")
new_size = (int(width / self.scaling_factor), int(height / self.scaling_factor))
lr_img = np.asarray(Image.fromarray(hr_img).resize(new_size))
lr_img = np.clip(lr_img, 0.0, 255.0).astype(np.uint8)

lr_height, lr_width = lr_img.shape[0:2]

# Sanity check
assert (
hr_width == lr_width * self.scaling_factor
and hr_height == lr_height * self.scaling_factor
)

lr_img_tensor = torch.from_numpy(lr_img.transpose((2, 0, 1))).contiguous()
lr_img_tensor = lr_img_tensor.to(dtype=torch.float32).div(255)

hr_img_tensor = torch.from_numpy(hr_img.transpose((2, 0, 1))).contiguous()
hr_img_tensor = hr_img_tensor.to(dtype=torch.float32).div(255)

return lr_img_tensor, hr_img_tensor

def _download_data(self) -> None:
BSD300_ASSET.fetch(extract=True)
self._prepare_data()
117 changes: 117 additions & 0 deletions qai_hub_models/datasets/coco.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import os
from typing import Tuple, Union

import torch
from torch.utils.data.dataloader import default_collate
from torchvision.datasets.coco import CocoDetection

from qai_hub_models.datasets.common import BaseDataset
from qai_hub_models.utils.asset_loaders import CachedWebDatasetAsset
from qai_hub_models.utils.image_processing import app_to_net_image_inputs

DATASET_ID = "coco"
DATASET_ASSET_VERSION = 1
COCO_DATASET = CachedWebDatasetAsset(
"http://images.cocodataset.org/zips/val2017.zip",
DATASET_ID,
DATASET_ASSET_VERSION,
"val2017.zip",
)
COCO_ANNOTATIONS = CachedWebDatasetAsset(
"http://images.cocodataset.org/annotations/annotations_trainval2017.zip",
DATASET_ID,
DATASET_ASSET_VERSION,
"annotations_trainval2017.zip",
)


def collate_fn(batch):
try:
image, gt = batch[0][0], batch[0][1]
image_id, height, width, boxes, labels = gt
new_list = []
new_list.append(default_collate([i for i in image if torch.is_tensor(i)]))
target = (
torch.tensor(image_id),
torch.tensor(height),
torch.tensor(width),
default_collate([i for i in boxes if torch.is_tensor(i)]),
default_collate([i for i in labels if torch.is_tensor(i)]),
)
new_list.append(target)
return new_list
except Exception:
return [], ([], [], [], [], [])


class CocoDataset(BaseDataset, CocoDetection):
"""
Class for using the COCODetection dataset published here:
Contains ~5k images spanning 80 classes.
"""

def __init__(self, target_image_size: Union[int, Tuple[int, int]] = 640):
BaseDataset.__init__(self, str(COCO_DATASET.path(extracted=True)))
CocoDetection.__init__(
self,
root=COCO_DATASET.path() / "val2017",
annFile=COCO_ANNOTATIONS.path() / "annotations" / "instances_val2017.json",
)

categories = self.coco.loadCats(self.coco.getCatIds())
categories.sort(key=lambda x: x["id"])
self.label_map = {}
counter = 0
for c in categories:
self.label_map[c["id"]] = counter
counter += 1
self.target_image_size = (
target_image_size
if isinstance(target_image_size, tuple)
else (target_image_size, target_image_size)
)

def __getitem__(self, item):
image, target = super(CocoDataset, self).__getitem__(item)
width, height = image.size
boxes = []
labels = []
if len(target) == 0:
return None, (None, None)
for annotation in target:
bbox = annotation.get("bbox")
boxes.append(
[
bbox[0] / width,
bbox[1] / height,
(bbox[0] + bbox[2]) / width,
(bbox[1] + bbox[3]) / height,
]
)
labels.append(self.label_map[annotation.get("category_id")])
boxes = torch.tensor(boxes)
labels = torch.tensor(labels)
image = image.resize(self.target_image_size)
image = app_to_net_image_inputs(image)[1]
return image, (target[0]["image_id"], height, width, boxes, labels)

def _validate_data(self) -> bool:
# Check validation data exists
if not COCO_DATASET.path().exists():
return False

# Check annotations exist
if not COCO_ANNOTATIONS.path().exists():
return False

# Ensure there are 5000 samples
if len(os.listdir(COCO_DATASET.path() / "val2017")) < 5000:
return False

return True

def _download_data(self) -> None:
COCO_DATASET.fetch(extract=True)
COCO_ANNOTATIONS.fetch(extract=True)
Loading

0 comments on commit 6dc1348

Please sign in to comment.