From 8fd49660d875f60cb1682cd9fe6a43426564399b Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Sat, 18 Apr 2020 20:09:14 -0300 Subject: [PATCH 01/27] initial draft --- awswrangler/db.py | 36 ++++++++++---- awswrangler/torch.py | 111 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 139 insertions(+), 8 deletions(-) create mode 100644 awswrangler/torch.py diff --git a/awswrangler/db.py b/awswrangler/db.py index 491fe7784..42d22fe73 100644 --- a/awswrangler/db.py +++ b/awswrangler/db.py @@ -155,6 +155,18 @@ def read_sql_query( ... ) """ + return _read_sql_query(fn=_record2df, sql=sql, con=con, index_col=index_col, params=params, chunksize=chunksize, dtype=dtype) + + +def _read_sql_query( + sql: str, + con: sqlalchemy.engine.Engine, + index_col: Optional[Union[str, List[str]]] = None, + params: Optional[Union[List, Tuple, Dict]] = None, + chunksize: Optional[int] = None, + dtype: Optional[Dict[str, pa.DataType]] = None, + fn: Callable, +): if not isinstance(con, sqlalchemy.engine.Engine): # pragma: no cover raise exceptions.InvalidConnection( "Invalid 'con' argument, please pass a " @@ -165,19 +177,27 @@ def read_sql_query( args = _convert_params(sql, params) cursor = _con.execute(*args) if chunksize is None: - return _records2df(records=cursor.fetchall(), cols_names=cursor.keys(), index=index_col, dtype=dtype) - return _iterate_cursor(cursor=cursor, chunksize=chunksize, index=index_col, dtype=dtype) + return fn(records=cursor.fetchall(), cols_names=cursor.keys(), index=index_col, dtype=dtype) + return _iterate_cursor(fn=fn, cursor=cursor, chunksize=chunksize, index=index_col, dtype=dtype) def _iterate_cursor( cursor, chunksize: int, index: Optional[Union[str, List[str]]], dtype: Optional[Dict[str, pa.DataType]] = None -) -> Iterator[pd.DataFrame]: +) -> Iterator[Any]: while True: records = cursor.fetchmany(chunksize) - if not records: - break - df: pd.DataFrame = _records2df(records=records, cols_names=cursor.keys(), index=index, dtype=dtype) - yield df + if not records: break + yield fn(records=records, cols_names=cursor.keys(), index=index, dtype=dtype) + + +def _records2numpy( + records: List[Tuple[Any]], + cols_names: List[str], + index: Optional[Union[str, List[str]]], + dtype: Optional[Dict[str, pa.DataType]] = None, +) -> Iterator[np.ndarry]: + for record in records: + yield np.array(record, float) def _records2df( @@ -191,7 +211,7 @@ def _records2df( if (dtype is None) or (col_name not in dtype): array: pa.Array = pa.array(obj=col_values, safe=True) # Creating Arrow array else: - array = pa.array(obj=col_values, type=dtype[col_name], safe=True) # Creating Arrow array with dtype + array: pa.Array = pa.array(obj=col_values, type=dtype[col_name], safe=True) # Creating Arrow array with dtype arrays.append(array) table = pa.Table.from_arrays(arrays=arrays, names=cols_names) # Creating arrow Table df: pd.DataFrame = table.to_pandas( # Creating Pandas DataFrame diff --git a/awswrangler/torch.py b/awswrangler/torch.py new file mode 100644 index 000000000..00cc273f0 --- /dev/null +++ b/awswrangler/torch.py @@ -0,0 +1,111 @@ +"""PyTorch Module.""" + +from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union + +import torch +import boto3 # type: ignore +import botocore.exceptions # type: ignore +import pandas as pd # type: ignore +import pandas.io.parsers # type: ignore +import pyarrow as pa # type: ignore +import pyarrow.lib # type: ignore +import pyarrow.parquet # type: ignore +import s3fs # type: ignore +from boto3.s3.transfer import TransferConfig # type: ignore +from pandas.io.common import infer_compression # type: ignore +from torch.utils.data import Dataset, IterableDataset + +from awswrangler import _data_types, _utils, catalog, exceptions, s3 + +_logger: logging.Logger = logging.getLogger(__name__) + + +class S3Dataset(Dataset): + """PyTorch Map-Style S3 Dataset. + + Parameters + ---------- + path : Union[str, List[str]] + S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + boto3_session : boto3.Session(), optional + Boto3 Session. The default boto3 session will be used if boto3_session receive None. + + Returns + ------- + torch.utils.data.Dataset + + Examples + -------- + >>> import awswrangler as wr + >>> import boto3 + >>> label_fn = lambda path: path.split[0][-2] + >>> ds = wr.torch.S3Dataset('s3://bucket/path', label_fn, boto3.Session()) + + """ + def __init__(self, path: Union[str, List[str]], label_fn, boto3_session): + super(S3IterableDataset).__init__() + self.label_fn = label_fn + self.paths: List[str] = s3._path2list( + path=path, + boto3_session=self.boto3_session + ) + self._s3 = boto3_session.resource('s3') + + def _fetch_obj(self, path): + obj = _s3.Object(bucket_name, key).get() + return obj['Body'].read() + + def __getitem__(self, index): + path = self.paths[index]) + return [self._fetch_obj(path), label_fn(path)] + + def __len__(self): + return len(self.paths) + + +class SQLDataset(torch.utils.data.IterableDataset): + """PyTorch Iterable SQL Dataset. + + Parameters + ---------- + path : Union[str, List[str]] + S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + boto3_session : boto3.Session(), optional + Boto3 Session. The default boto3 session will be used if boto3_session receive None. + + Returns + ------- + torch.utils.data.Dataset + + Examples + -------- + >>> import awswrangler as wr + >>> con = wr.catalog.get_engine("aws-data-wrangler-postgresql") + >>> ds = wr.torch.SQLDataset('select * from public.tutorial', con=con) + + """ + def __init__(self, ): + super(SQLDataset).__init__( + sql: str, + con: sqlalchemy.engine.Engine, + index_col: Optional[Union[str, List[str]]] = None, + ): + self.sql = sql + self.con = con + self.index_col = index_col + + def __iter__(self): + worker_info = torch.utils.data.get_worker_info() + if worker_info is None: # single-process data loading, return the full iterator + pass + else: # in a worker process + raise NotImplemented() + + for ds in wr.db._read_sql_query( + fn=wr.db._records2numpy, + sql=self.sql, + con=self.con, + index_col=self.index_col, + ): + for row in ds: + yield row From 863ba2698fd97411edb5a82a9f22c176852f5093 Mon Sep 17 00:00:00 2001 From: igorborgest Date: Sun, 19 Apr 2020 09:16:54 -0300 Subject: [PATCH 02/27] adding Pytorch as a development dependency --- requirements-dev.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 3fdd3cdf3..137f57383 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -17,4 +17,6 @@ twine~=3.1.1 wheel~=0.34.2 sphinx~=3.0.1 sphinx_bootstrap_theme~=0.7.1 -moto~=1.3.14 \ No newline at end of file +moto~=1.3.14 +torch~=1.4.0 +torchvision~=0.5.0 \ No newline at end of file From 2864dc09c2851a44661f1a875d3b6e47ec1f0017 Mon Sep 17 00:00:00 2001 From: igorborgest Date: Sun, 19 Apr 2020 09:52:41 -0300 Subject: [PATCH 03/27] Cleaning up initial draft --- awswrangler/db.py | 27 ++++--- awswrangler/torch.py | 173 ++++++++++++++++++++----------------------- 2 files changed, 95 insertions(+), 105 deletions(-) diff --git a/awswrangler/db.py b/awswrangler/db.py index 42d22fe73..f4508d09c 100644 --- a/awswrangler/db.py +++ b/awswrangler/db.py @@ -2,10 +2,11 @@ import json import logging -from typing import Any, Dict, Iterator, List, Optional, Tuple, Union +from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union from urllib.parse import quote_plus import boto3 # type: ignore +import numpy as np # type: ignore import pandas as pd # type: ignore import pyarrow as pa # type: ignore import sqlalchemy # type: ignore @@ -155,17 +156,19 @@ def read_sql_query( ... ) """ - return _read_sql_query(fn=_record2df, sql=sql, con=con, index_col=index_col, params=params, chunksize=chunksize, dtype=dtype) + return _read_sql_query( + fn=_records2df, sql=sql, con=con, index_col=index_col, params=params, chunksize=chunksize, dtype=dtype + ) def _read_sql_query( + fn: Callable, sql: str, con: sqlalchemy.engine.Engine, index_col: Optional[Union[str, List[str]]] = None, params: Optional[Union[List, Tuple, Dict]] = None, chunksize: Optional[int] = None, dtype: Optional[Dict[str, pa.DataType]] = None, - fn: Callable, ): if not isinstance(con, sqlalchemy.engine.Engine): # pragma: no cover raise exceptions.InvalidConnection( @@ -182,20 +185,20 @@ def _read_sql_query( def _iterate_cursor( - cursor, chunksize: int, index: Optional[Union[str, List[str]]], dtype: Optional[Dict[str, pa.DataType]] = None + fn: Callable, + cursor, + chunksize: int, + index: Optional[Union[str, List[str]]], + dtype: Optional[Dict[str, pa.DataType]] = None, ) -> Iterator[Any]: while True: records = cursor.fetchmany(chunksize) - if not records: break + if not records: + break yield fn(records=records, cols_names=cursor.keys(), index=index, dtype=dtype) -def _records2numpy( - records: List[Tuple[Any]], - cols_names: List[str], - index: Optional[Union[str, List[str]]], - dtype: Optional[Dict[str, pa.DataType]] = None, -) -> Iterator[np.ndarry]: +def _records2numpy(records: List[Tuple[Any]], **kwargs) -> Iterator[np.ndarry]: # pylint: disable=unused-argument for record in records: yield np.array(record, float) @@ -211,7 +214,7 @@ def _records2df( if (dtype is None) or (col_name not in dtype): array: pa.Array = pa.array(obj=col_values, safe=True) # Creating Arrow array else: - array: pa.Array = pa.array(obj=col_values, type=dtype[col_name], safe=True) # Creating Arrow array with dtype + array = pa.array(obj=col_values, type=dtype[col_name], safe=True) # Creating Arrow array with dtype arrays.append(array) table = pa.Table.from_arrays(arrays=arrays, names=cols_names) # Creating arrow Table df: pd.DataFrame = table.to_pandas( # Creating Pandas DataFrame diff --git a/awswrangler/torch.py b/awswrangler/torch.py index 00cc273f0..afe85f1de 100644 --- a/awswrangler/torch.py +++ b/awswrangler/torch.py @@ -1,111 +1,98 @@ """PyTorch Module.""" -from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union +import logging +import sqlalchemy # type: ignore import torch -import boto3 # type: ignore -import botocore.exceptions # type: ignore -import pandas as pd # type: ignore -import pandas.io.parsers # type: ignore -import pyarrow as pa # type: ignore -import pyarrow.lib # type: ignore -import pyarrow.parquet # type: ignore -import s3fs # type: ignore -from boto3.s3.transfer import TransferConfig # type: ignore -from pandas.io.common import infer_compression # type: ignore -from torch.utils.data import Dataset, IterableDataset - -from awswrangler import _data_types, _utils, catalog, exceptions, s3 +from torch.utils.data.dataset import IterableDataset + +from awswrangler import db _logger: logging.Logger = logging.getLogger(__name__) -class S3Dataset(Dataset): - """PyTorch Map-Style S3 Dataset. - - Parameters - ---------- - path : Union[str, List[str]] - S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). - boto3_session : boto3.Session(), optional - Boto3 Session. The default boto3 session will be used if boto3_session receive None. - - Returns - ------- - torch.utils.data.Dataset - - Examples - -------- - >>> import awswrangler as wr - >>> import boto3 - >>> label_fn = lambda path: path.split[0][-2] - >>> ds = wr.torch.S3Dataset('s3://bucket/path', label_fn, boto3.Session()) - - """ - def __init__(self, path: Union[str, List[str]], label_fn, boto3_session): - super(S3IterableDataset).__init__() - self.label_fn = label_fn - self.paths: List[str] = s3._path2list( - path=path, - boto3_session=self.boto3_session - ) - self._s3 = boto3_session.resource('s3') - - def _fetch_obj(self, path): - obj = _s3.Object(bucket_name, key).get() - return obj['Body'].read() - - def __getitem__(self, index): - path = self.paths[index]) - return [self._fetch_obj(path), label_fn(path)] - - def __len__(self): - return len(self.paths) - - -class SQLDataset(torch.utils.data.IterableDataset): - """PyTorch Iterable SQL Dataset. - - Parameters - ---------- - path : Union[str, List[str]] - S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). - boto3_session : boto3.Session(), optional - Boto3 Session. The default boto3 session will be used if boto3_session receive None. - - Returns - ------- - torch.utils.data.Dataset - - Examples - -------- - >>> import awswrangler as wr - >>> con = wr.catalog.get_engine("aws-data-wrangler-postgresql") - >>> ds = wr.torch.SQLDataset('select * from public.tutorial', con=con) - - """ - def __init__(self, ): - super(SQLDataset).__init__( - sql: str, - con: sqlalchemy.engine.Engine, - index_col: Optional[Union[str, List[str]]] = None, - ): +# class S3Dataset(Dataset): +# """PyTorch Map-Style S3 Dataset. +# +# Parameters +# ---------- +# path : Union[str, List[str]] +# S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). +# boto3_session : boto3.Session(), optional +# Boto3 Session. The default boto3 session will be used if boto3_session receive None. +# +# Returns +# ------- +# torch.utils.data.Dataset +# +# Examples +# -------- +# >>> import awswrangler as wr +# >>> import boto3 +# >>> label_fn = lambda path: path.split[0][-2] +# >>> ds = wr.torch.S3Dataset('s3://bucket/path', label_fn, boto3.Session()) +# +# """ +# def __init__(self, path: Union[str, List[str]], label_fn, boto3_session): +# super(S3IterableDataset).__init__() +# self.label_fn = label_fn +# self.paths: List[str] = s3._path2list( +# path=path, +# boto3_session=self.boto3_session +# ) +# self._s3 = boto3_session.resource('s3') +# +# def _fetch_obj(self, path): +# obj = _s3.Object(bucket_name, key).get() +# return obj['Body'].read() +# +# def __getitem__(self, index): +# path = self.paths[index]) +# return [self._fetch_obj(path), label_fn(path)] +# +# def __len__(self): +# return len(self.paths) + + +class SQLDataset(IterableDataset): # pylint: disable=too-few-public-methods,abstract-method + """Pytorch Iterable SQL Dataset.""" + + def __init__(self, sql: str, con: sqlalchemy.engine.Engine): + """Pytorch Iterable SQL Dataset. + + Support for **Redshift**, **PostgreSQL** and **MySQL**. + + Parameters + ---------- + sql : str + Pandas DataFrame https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html + con : sqlalchemy.engine.Engine + SQLAlchemy Engine. Please use, + wr.db.get_engine(), wr.db.get_redshift_temp_engine() or wr.catalog.get_engine() + + Returns + ------- + torch.utils.data.dataset.IterableDataset + + Examples + -------- + >>> import awswrangler as wr + >>> con = wr.catalog.get_engine("aws-data-wrangler-postgresql") + >>> ds = wr.torch.SQLDataset('select * from public.tutorial', con=con) + + """ + super().__init__() self.sql = sql self.con = con - self.index_col = index_col def __iter__(self): + """Iterate over the Dataset.""" worker_info = torch.utils.data.get_worker_info() if worker_info is None: # single-process data loading, return the full iterator pass else: # in a worker process - raise NotImplemented() - - for ds in wr.db._read_sql_query( - fn=wr.db._records2numpy, - sql=self.sql, - con=self.con, - index_col=self.index_col, - ): + raise NotImplementedError() + + for ds in db._read_sql_query(fn=db._records2numpy, sql=self.sql, con=self.con): for row in ds: yield row From 4fed4c7f5f743e90dbb16b8678b5cd9a104ae3ed Mon Sep 17 00:00:00 2001 From: igorborgest Date: Sun, 19 Apr 2020 13:53:07 -0300 Subject: [PATCH 04/27] Add first test --- awswrangler/__init__.py | 2 +- awswrangler/db.py | 5 +- awswrangler/s3.py | 9 +- awswrangler/torch.py | 127 ++++++++++++++++--------- pytest.ini | 2 +- testing/test_awswrangler/test_torch.py | 99 +++++++++++++++++++ 6 files changed, 188 insertions(+), 56 deletions(-) create mode 100644 testing/test_awswrangler/test_torch.py diff --git a/awswrangler/__init__.py b/awswrangler/__init__.py index ce11c7ad5..ff6a2bd71 100644 --- a/awswrangler/__init__.py +++ b/awswrangler/__init__.py @@ -7,7 +7,7 @@ import logging -from awswrangler import athena, catalog, cloudwatch, db, emr, exceptions, s3 # noqa +from awswrangler import athena, catalog, cloudwatch, db, emr, exceptions, s3, torch # noqa from awswrangler.__metadata__ import __description__, __license__, __title__, __version__ # noqa logging.getLogger("awswrangler").addHandler(logging.NullHandler()) diff --git a/awswrangler/db.py b/awswrangler/db.py index f4508d09c..78979787c 100644 --- a/awswrangler/db.py +++ b/awswrangler/db.py @@ -198,9 +198,8 @@ def _iterate_cursor( yield fn(records=records, cols_names=cursor.keys(), index=index, dtype=dtype) -def _records2numpy(records: List[Tuple[Any]], **kwargs) -> Iterator[np.ndarry]: # pylint: disable=unused-argument - for record in records: - yield np.array(record, float) +def _records2numpy(records: List[Tuple[Any]], **kwargs) -> Iterator[np.ndarray]: # pylint: disable=unused-argument + return np.array(records, dtype=float) def _records2df( diff --git a/awswrangler/s3.py b/awswrangler/s3.py index f728937db..157607d8c 100644 --- a/awswrangler/s3.py +++ b/awswrangler/s3.py @@ -111,7 +111,7 @@ def does_object_exist(path: str, boto3_session: Optional[boto3.Session] = None) raise ex # pragma: no cover -def list_objects(path: str, boto3_session: Optional[boto3.Session] = None) -> List[str]: +def list_objects(path: str, suffix: Optional[str] = None, boto3_session: Optional[boto3.Session] = None) -> List[str]: """List Amazon S3 objects from a prefix. Parameters @@ -155,15 +155,16 @@ def list_objects(path: str, boto3_session: Optional[boto3.Session] = None) -> Li for content in contents: if (content is not None) and ("Key" in content): key: str = content["Key"] - paths.append(f"s3://{bucket}/{key}") + if (suffix is None) or key.endswith(suffix): + paths.append(f"s3://{bucket}/{key}") return paths -def _path2list(path: Union[str, List[str]], boto3_session: Optional[boto3.Session]) -> List[str]: +def _path2list(path: Union[str, List[str]], boto3_session: Optional[boto3.Session], suffix: Optional[str] = None) -> List[str]: if isinstance(path, str): # prefix paths: List[str] = list_objects(path=path, boto3_session=boto3_session) elif isinstance(path, list): - paths = path + paths = path if suffix is None else [x for x in path if x.endswith(suffix)] else: raise exceptions.InvalidArgumentType(f"{type(path)} is not a valid path type. Please, use str or List[str].") return paths diff --git a/awswrangler/torch.py b/awswrangler/torch.py index afe85f1de..7d84be981 100644 --- a/awswrangler/torch.py +++ b/awswrangler/torch.py @@ -1,63 +1,93 @@ """PyTorch Module.""" import logging +from io import BytesIO +from typing import Optional, Union, List import sqlalchemy # type: ignore +import numpy as np # type: ignore +import boto3 # type: ignore import torch -from torch.utils.data.dataset import IterableDataset +from torch.utils.data.dataset import Dataset, IterableDataset +from PIL import Image +from torchvision.transforms.functional import to_tensor -from awswrangler import db +from awswrangler import db, s3, _utils _logger: logging.Logger = logging.getLogger(__name__) -# class S3Dataset(Dataset): -# """PyTorch Map-Style S3 Dataset. -# -# Parameters -# ---------- -# path : Union[str, List[str]] -# S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). -# boto3_session : boto3.Session(), optional -# Boto3 Session. The default boto3 session will be used if boto3_session receive None. -# -# Returns -# ------- -# torch.utils.data.Dataset -# -# Examples -# -------- -# >>> import awswrangler as wr -# >>> import boto3 -# >>> label_fn = lambda path: path.split[0][-2] -# >>> ds = wr.torch.S3Dataset('s3://bucket/path', label_fn, boto3.Session()) -# -# """ -# def __init__(self, path: Union[str, List[str]], label_fn, boto3_session): -# super(S3IterableDataset).__init__() -# self.label_fn = label_fn -# self.paths: List[str] = s3._path2list( -# path=path, -# boto3_session=self.boto3_session -# ) -# self._s3 = boto3_session.resource('s3') -# -# def _fetch_obj(self, path): -# obj = _s3.Object(bucket_name, key).get() -# return obj['Body'].read() -# -# def __getitem__(self, index): -# path = self.paths[index]) -# return [self._fetch_obj(path), label_fn(path)] -# -# def __len__(self): -# return len(self.paths) +class _BaseS3Dataset(Dataset): + """PyTorch Map-Style S3 Dataset. + + Parameters + ---------- + path : Union[str, List[str]] + S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + boto3_session : boto3.Session(), optional + Boto3 Session. The default boto3 session will be used if boto3_session receive None. + + Returns + ------- + torch.utils.data.Dataset + + Examples + -------- + >>> import awswrangler as wr + >>> import boto3 + >>> label_fn = lambda path: path.split[0][-2] + >>> ds = wr.torch.S3Dataset('s3://bucket/path', label_fn, boto3.Session()) + + """ + def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session): + super().__init__() + self.session = _utils.ensure_session(session=boto3_session) + self.paths: List[str] = s3._path2list( + path=path, + suffix=suffix, + boto3_session=self.session + ) + + def __getitem__(self, index): + path = self.paths[index] + obj = self._fetch_obj(path) + return [self.parser_fn(obj), self.label_fn(path)] + + def __len__(self): + return len(self.paths) + + def _fetch_obj(self, path): + bucket, key = _utils.parse_path(path=path) + buff = BytesIO() + client_s3: boto3.client = _utils.client(service_name="s3", session=self.session) + client_s3.download_fileobj(Bucket=bucket, Key=key, Fileobj=buff) + return buff.seek(0) + + def parser_fn(self, obj): + pass + + def label_fn(self, obj): + pass + + +class ImageS3Dataset(Dataset): + + @staticmethod + def parser_fn(obj): + image = Image.open('YOUR_PATH') + tensor = to_tensor(image) + tensor.unsqueeze_(0) + return tensor + + @staticmethod + def label_fn(obj): + pass class SQLDataset(IterableDataset): # pylint: disable=too-few-public-methods,abstract-method """Pytorch Iterable SQL Dataset.""" - def __init__(self, sql: str, con: sqlalchemy.engine.Engine): + def __init__(self, sql: str, con: sqlalchemy.engine.Engine, chunksize: Optional[int] = None,): """Pytorch Iterable SQL Dataset. Support for **Redshift**, **PostgreSQL** and **MySQL**. @@ -84,6 +114,7 @@ def __init__(self, sql: str, con: sqlalchemy.engine.Engine): super().__init__() self.sql = sql self.con = con + self.chunksize = chunksize def __iter__(self): """Iterate over the Dataset.""" @@ -92,7 +123,9 @@ def __iter__(self): pass else: # in a worker process raise NotImplementedError() - - for ds in db._read_sql_query(fn=db._records2numpy, sql=self.sql, con=self.con): + ret = db._read_sql_query(fn=db._records2numpy, sql=self.sql, con=self.con, chunksize=self.chunksize) + if isinstance(ret, np.ndarray): + ret = [ret] + for ds in ret: for row in ds: - yield row + yield torch.as_tensor(row, dtype=torch.float) diff --git a/pytest.ini b/pytest.ini index 8e7a47ef1..d233cbf74 100644 --- a/pytest.ini +++ b/pytest.ini @@ -1,7 +1,7 @@ [pytest] addopts = --verbose - --capture=fd + --capture=no filterwarnings = ignore::DeprecationWarning ignore::UserWarning \ No newline at end of file diff --git a/testing/test_awswrangler/test_torch.py b/testing/test_awswrangler/test_torch.py new file mode 100644 index 000000000..4725f1ea4 --- /dev/null +++ b/testing/test_awswrangler/test_torch.py @@ -0,0 +1,99 @@ +import logging + +import boto3 +import pandas as pd +import pytest +import torch + +import awswrangler as wr + +logging.basicConfig(level=logging.INFO, format="[%(asctime)s][%(levelname)s][%(name)s][%(funcName)s] %(message)s") +logging.getLogger("awswrangler").setLevel(logging.DEBUG) +logging.getLogger("botocore.credentials").setLevel(logging.CRITICAL) + + +@pytest.fixture(scope="module") +def cloudformation_outputs(): + response = boto3.client("cloudformation").describe_stacks(StackName="aws-data-wrangler-test") + outputs = {} + for output in response.get("Stacks")[0].get("Outputs"): + outputs[output.get("OutputKey")] = output.get("OutputValue") + yield outputs + + +@pytest.fixture(scope="module") +def bucket(cloudformation_outputs): + if "BucketName" in cloudformation_outputs: + bucket = cloudformation_outputs["BucketName"] + else: + raise Exception("You must deploy/update the test infrastructure (CloudFormation)") + yield bucket + + +@pytest.fixture(scope="module") +def parameters(cloudformation_outputs): + parameters = dict(postgresql={}, mysql={}, redshift={}) + parameters["postgresql"]["host"] = cloudformation_outputs["PostgresqlAddress"] + parameters["postgresql"]["port"] = 3306 + parameters["postgresql"]["schema"] = "public" + parameters["postgresql"]["database"] = "postgres" + parameters["mysql"]["host"] = cloudformation_outputs["MysqlAddress"] + parameters["mysql"]["port"] = 3306 + parameters["mysql"]["schema"] = "test" + parameters["mysql"]["database"] = "test" + parameters["redshift"]["host"] = cloudformation_outputs["RedshiftAddress"] + parameters["redshift"]["port"] = cloudformation_outputs["RedshiftPort"] + parameters["redshift"]["identifier"] = cloudformation_outputs["RedshiftIdentifier"] + parameters["redshift"]["schema"] = "public" + parameters["redshift"]["database"] = "test" + parameters["redshift"]["role"] = cloudformation_outputs["RedshiftRole"] + parameters["password"] = cloudformation_outputs["DatabasesPassword"] + parameters["user"] = "test" + yield parameters + + +@pytest.mark.parametrize("db_type, chunksize", [ + ("mysql", None), + ("redshift", None), + ("postgresql", None), + ("mysql", 1), + ("redshift", 1), + ("postgresql", 1), +]) +def test_torch_sql(parameters, db_type, chunksize): + schema = parameters[db_type]["schema"] + table = "test_torch_sql" + engine = wr.catalog.get_engine(connection=f"aws-data-wrangler-{db_type}") + wr.db.to_sql( + df=pd.DataFrame({"a": [1.0, 2.0, 3.0], "b": [4.0, 5.0, 6.0]}), + con=engine, + name=table, + schema=schema, + if_exists="replace", + index=False, + index_label=None, + chunksize=None, + method=None + ) + ds = list(wr.torch.SQLDataset(f"SELECT * FROM {schema}.{table}", con=engine, chunksize=chunksize)) + assert torch.all(ds[0].eq(torch.tensor([1.0, 4.0]))) + assert torch.all(ds[1].eq(torch.tensor([2.0, 5.0]))) + assert torch.all(ds[2].eq(torch.tensor([3.0, 6.0]))) + + +def test_torch_sql(parameters, db_type, chunksize): + schema = parameters[db_type]["schema"] + table = "test_torch_sql" + engine = wr.catalog.get_engine(connection=f"aws-data-wrangler-{db_type}") + wr.db.to_sql( + df=pd.DataFrame({"a": [1.0, 2.0, 3.0], "b": [4.0, 5.0, 6.0]}), + con=engine, + name=table, + schema=schema, + if_exists="replace", + index=False, + index_label=None, + chunksize=None, + method=None + ) + From 72c739c905f3a34545ffc71da7693ff4baf029c1 Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Sun, 19 Apr 2020 18:58:13 -0300 Subject: [PATCH 05/27] add audio and image dataset --- awswrangler/s3.py | 4 +- awswrangler/torch.py | 169 ++++++++++++++++++++----- testing/test_awswrangler/test_torch.py | 32 +++-- 3 files changed, 159 insertions(+), 46 deletions(-) diff --git a/awswrangler/s3.py b/awswrangler/s3.py index 157607d8c..f2f869ac2 100644 --- a/awswrangler/s3.py +++ b/awswrangler/s3.py @@ -120,6 +120,8 @@ def list_objects(path: str, suffix: Optional[str] = None, boto3_session: Optiona S3 path (e.g. s3://bucket/prefix). boto3_session : boto3.Session(), optional Boto3 Session. The default boto3 session will be used if boto3_session receive None. + suffix: str, optional + Suffix for filtering S3 keys Returns ------- @@ -160,7 +162,7 @@ def list_objects(path: str, suffix: Optional[str] = None, boto3_session: Optiona return paths -def _path2list(path: Union[str, List[str]], boto3_session: Optional[boto3.Session], suffix: Optional[str] = None) -> List[str]: +def _path2list(path: object, boto3_session: boto3.Session, suffix: str = None) -> List[str]: if isinstance(path, str): # prefix paths: List[str] = list_objects(path=path, boto3_session=boto3_session) elif isinstance(path, list): diff --git a/awswrangler/torch.py b/awswrangler/torch.py index 7d84be981..a5b6497d8 100644 --- a/awswrangler/torch.py +++ b/awswrangler/torch.py @@ -1,5 +1,6 @@ """PyTorch Module.""" +import re import logging from io import BytesIO from typing import Optional, Union, List @@ -9,8 +10,7 @@ import boto3 # type: ignore import torch from torch.utils.data.dataset import Dataset, IterableDataset -from PIL import Image -from torchvision.transforms.functional import to_tensor + from awswrangler import db, s3, _utils @@ -18,34 +18,29 @@ class _BaseS3Dataset(Dataset): - """PyTorch Map-Style S3 Dataset. + """PyTorch Map-Style S3 Dataset.""" - Parameters - ---------- - path : Union[str, List[str]] - S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). - boto3_session : boto3.Session(), optional - Boto3 Session. The default boto3 session will be used if boto3_session receive None. + def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session): + """PyTorch Map-Style S3 Dataset. - Returns - ------- - torch.utils.data.Dataset + Parameters + ---------- + path : Union[str, List[str]] + S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + boto3_session : boto3.Session(), optional + Boto3 Session. The default boto3 session will be used if boto3_session receive None. - Examples - -------- - >>> import awswrangler as wr - >>> import boto3 - >>> label_fn = lambda path: path.split[0][-2] - >>> ds = wr.torch.S3Dataset('s3://bucket/path', label_fn, boto3.Session()) + Returns + ------- + torch.utils.data.Dataset - """ - def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session): + """ super().__init__() self.session = _utils.ensure_session(session=boto3_session) self.paths: List[str] = s3._path2list( path=path, suffix=suffix, - boto3_session=self.session + boto3_session=self.session, ) def __getitem__(self, index): @@ -66,28 +61,139 @@ def _fetch_obj(self, path): def parser_fn(self, obj): pass - def label_fn(self, obj): + def label_fn(self, path): pass -class ImageS3Dataset(Dataset): +class _S3PartitionedDataset(_BaseS3Dataset): + + def label_fn(self, path): + return int(re.findall(r'/(.*?)=(.*?)/', path)[-1][1]) + + +class AudioS3Dataset(_S3PartitionedDataset): + + def __init__(self): + """PyTorch S3 Audio Dataset. + + Assumes audio files are stored with the following structure: + + bucket + ├── class=0 + │ ├── audio0.wav + │ └── audio1.wav + └── class=1 + ├── audio2.wav + └── audio3.wav + + Parameters + ---------- + path : Union[str, List[str]] + S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + boto3_session : boto3.Session(), optional + Boto3 Session. The default boto3 session will be used if boto3_session receive None. + + Returns + ------- + torch.utils.data.Dataset + + Examples + -------- + >>> import awswrangler as wr + >>> import boto3 + >>> ds = wr.torch.AudioS3Dataset('s3://bucket/path', boto3.Session()) + + """ + super(AudioS3Dataset, self).__init__() + import torchaudio + + def parser_fn(self, obj): + waveform, sample_rate = torchaudio.load(obj) + return waveform, sample_rate + + +class LambdaS3Dataset(_BaseS3Dataset): + """PyTorch S3 Audio Dataset. + + Parameters + ---------- + path : Union[str, List[str]] + S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + boto3_session : boto3.Session(), optional + Boto3 Session. The default boto3 session will be used if boto3_session receive None. + + Returns + ------- + torch.utils.data.Dataset + + Examples + -------- + >>> import awswrangler as wr + >>> import boto3 + >>> parse_fn = lambda x: torch.tensor(x) + >>> label_fn = lambda x: x.split('.')[-1] + >>> ds = wr.torch.LambdaS3Dataset('s3://bucket/path', boto3.Session(), parse_fn=parse_fn, label_fn=label_fn) + + """ + def __init__(self, parse_fn, label_fn): + self._parse_fn = parse_fn + self._label_fn = label_fn + + def label_fn(self, path): + return self._label_fn(path) - @staticmethod - def parser_fn(obj): - image = Image.open('YOUR_PATH') + def parse_fn(self, obj): + return self._parse_fn(obj) + + +class ImageS3Dataset(_S3PartitionedDataset): + + def __init__(self): + """PyTorch Image S3 Dataset. + + Assumes Images are stored with the following structure: + + bucket + ├── class=0 + │ ├── img0.jpeg + │ └── img1.jpeg + └── class=1 + ├── img2.jpeg + └── img3.jpeg + + Parameters + ---------- + path : Union[str, List[str]] + S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + boto3_session : boto3.Session(), optional + Boto3 Session. The default boto3 session will be used if boto3_session receive None. + + Returns + ------- + torch.utils.data.Dataset + + Examples + -------- + >>> import awswrangler as wr + >>> import boto3 + >>> ds = wr.torch.ImageS3Dataset('s3://bucket/path', boto3.Session()) + + """ + super(ImageS3Dataset, self).__init__() + from PIL import Image + from torchvision.transforms.functional import to_tensor + + def parser_fn(self, obj): + image = Image.open(obj) tensor = to_tensor(image) tensor.unsqueeze_(0) return tensor - @staticmethod - def label_fn(obj): - pass - class SQLDataset(IterableDataset): # pylint: disable=too-few-public-methods,abstract-method """Pytorch Iterable SQL Dataset.""" - def __init__(self, sql: str, con: sqlalchemy.engine.Engine, chunksize: Optional[int] = None,): + def __init__(self, sql: str, con: sqlalchemy.engine.Engine, label_col: Optional[str], chunksize: Optional[int] = None,): """Pytorch Iterable SQL Dataset. Support for **Redshift**, **PostgreSQL** and **MySQL**. @@ -114,6 +220,7 @@ def __init__(self, sql: str, con: sqlalchemy.engine.Engine, chunksize: Optional[ super().__init__() self.sql = sql self.con = con + self.label_col = label_col self.chunksize = chunksize def __iter__(self): diff --git a/testing/test_awswrangler/test_torch.py b/testing/test_awswrangler/test_torch.py index 4725f1ea4..f30736c16 100644 --- a/testing/test_awswrangler/test_torch.py +++ b/testing/test_awswrangler/test_torch.py @@ -81,19 +81,23 @@ def test_torch_sql(parameters, db_type, chunksize): assert torch.all(ds[2].eq(torch.tensor([3.0, 6.0]))) -def test_torch_sql(parameters, db_type, chunksize): - schema = parameters[db_type]["schema"] - table = "test_torch_sql" - engine = wr.catalog.get_engine(connection=f"aws-data-wrangler-{db_type}") - wr.db.to_sql( - df=pd.DataFrame({"a": [1.0, 2.0, 3.0], "b": [4.0, 5.0, 6.0]}), - con=engine, - name=table, - schema=schema, - if_exists="replace", - index=False, - index_label=None, - chunksize=None, - method=None +def test_torch_image_s3(bucket): + s3 = boto3.client('s3') + ref_label = 0 + s3.put_object( + Body=open("../../docs/source/_static/logo.png"), + Bucket=bucket, + Key=f'class={ref_label}/logo.png', ) + ds = wr.torch.ImageS3Dataset() + for image, label in ds: + assert image.shape == torch.Size([1, 28, 28]) + assert label == torch.int(ref_label) + break + +# def test_torch_audio_s3(bucket): +# ds = wr.torch.AudioS3Dataset() +# for image, label in ds: +# assert image.shape == torch.Size([1, 28, 28]) +# break \ No newline at end of file From f72810ec53fb33a60df0b5c97fb5ab8059317f81 Mon Sep 17 00:00:00 2001 From: igorborgest Date: Mon, 20 Apr 2020 01:07:55 -0300 Subject: [PATCH 06/27] Add label_col to torch.SQLDataset --- awswrangler/db.py | 63 ++--- awswrangler/s3.py | 2 +- awswrangler/torch.py | 313 ++++++++++++++----------- testing/test_awswrangler/test_torch.py | 52 ++-- 4 files changed, 235 insertions(+), 195 deletions(-) diff --git a/awswrangler/db.py b/awswrangler/db.py index 78979787c..e69739433 100644 --- a/awswrangler/db.py +++ b/awswrangler/db.py @@ -6,7 +6,6 @@ from urllib.parse import quote_plus import boto3 # type: ignore -import numpy as np # type: ignore import pandas as pd # type: ignore import pyarrow as pa # type: ignore import sqlalchemy # type: ignore @@ -156,50 +155,15 @@ def read_sql_query( ... ) """ - return _read_sql_query( - fn=_records2df, sql=sql, con=con, index_col=index_col, params=params, chunksize=chunksize, dtype=dtype - ) - - -def _read_sql_query( - fn: Callable, - sql: str, - con: sqlalchemy.engine.Engine, - index_col: Optional[Union[str, List[str]]] = None, - params: Optional[Union[List, Tuple, Dict]] = None, - chunksize: Optional[int] = None, - dtype: Optional[Dict[str, pa.DataType]] = None, -): - if not isinstance(con, sqlalchemy.engine.Engine): # pragma: no cover - raise exceptions.InvalidConnection( - "Invalid 'con' argument, please pass a " - "SQLAlchemy Engine. Use wr.db.get_engine(), " - "wr.db.get_redshift_temp_engine() or wr.catalog.get_engine()" - ) + _validate_engine(con=con) with con.connect() as _con: args = _convert_params(sql, params) cursor = _con.execute(*args) if chunksize is None: - return fn(records=cursor.fetchall(), cols_names=cursor.keys(), index=index_col, dtype=dtype) - return _iterate_cursor(fn=fn, cursor=cursor, chunksize=chunksize, index=index_col, dtype=dtype) - - -def _iterate_cursor( - fn: Callable, - cursor, - chunksize: int, - index: Optional[Union[str, List[str]]], - dtype: Optional[Dict[str, pa.DataType]] = None, -) -> Iterator[Any]: - while True: - records = cursor.fetchmany(chunksize) - if not records: - break - yield fn(records=records, cols_names=cursor.keys(), index=index, dtype=dtype) - - -def _records2numpy(records: List[Tuple[Any]], **kwargs) -> Iterator[np.ndarray]: # pylint: disable=unused-argument - return np.array(records, dtype=float) + return _records2df(records=cursor.fetchall(), cols_names=cursor.keys(), index=index_col, dtype=dtype) + return _iterate_cursor( + fn=_records2df, cursor=cursor, chunksize=chunksize, cols_names=cursor.keys(), index=index_col, dtype=dtype + ) def _records2df( @@ -229,6 +193,14 @@ def _records2df( return df +def _iterate_cursor(fn: Callable, cursor: Any, chunksize: int, **kwargs) -> Iterator[Any]: + while True: + records = cursor.fetchmany(chunksize) + if not records: + break + yield fn(records=records, **kwargs) + + def _convert_params(sql: str, params: Optional[Union[List, Tuple, Dict]]) -> List[Any]: args: List[Any] = [sql] if params is not None: @@ -1109,3 +1081,12 @@ def unload_redshift_to_files( paths = [x[0].replace(" ", "") for x in _con.execute(sql).fetchall()] _logger.debug(f"paths: {paths}") return paths + + +def _validate_engine(con: sqlalchemy.engine.Engine) -> None: # pragma: no cover + if not isinstance(con, sqlalchemy.engine.Engine): + raise exceptions.InvalidConnection( + "Invalid 'con' argument, please pass a " + "SQLAlchemy Engine. Use wr.db.get_engine(), " + "wr.db.get_redshift_temp_engine() or wr.catalog.get_engine()" + ) diff --git a/awswrangler/s3.py b/awswrangler/s3.py index f2f869ac2..c083d52c5 100644 --- a/awswrangler/s3.py +++ b/awswrangler/s3.py @@ -121,7 +121,7 @@ def list_objects(path: str, suffix: Optional[str] = None, boto3_session: Optiona boto3_session : boto3.Session(), optional Boto3 Session. The default boto3 session will be used if boto3_session receive None. suffix: str, optional - Suffix for filtering S3 keys + Suffix for filtering S3 keys. Returns ------- diff --git a/awswrangler/torch.py b/awswrangler/torch.py index a5b6497d8..b27422750 100644 --- a/awswrangler/torch.py +++ b/awswrangler/torch.py @@ -3,16 +3,15 @@ import re import logging from io import BytesIO -from typing import Optional, Union, List +from typing import Any, Iterator, List, Optional, Tuple, Union -import sqlalchemy # type: ignore import numpy as np # type: ignore +import sqlalchemy # type: ignore import boto3 # type: ignore import torch from torch.utils.data.dataset import Dataset, IterableDataset - -from awswrangler import db, s3, _utils +from awswrangler import db, _utils, s3 _logger: logging.Logger = logging.getLogger(__name__) @@ -71,129 +70,135 @@ def label_fn(self, path): return int(re.findall(r'/(.*?)=(.*?)/', path)[-1][1]) -class AudioS3Dataset(_S3PartitionedDataset): - - def __init__(self): - """PyTorch S3 Audio Dataset. - - Assumes audio files are stored with the following structure: - - bucket - ├── class=0 - │ ├── audio0.wav - │ └── audio1.wav - └── class=1 - ├── audio2.wav - └── audio3.wav - - Parameters - ---------- - path : Union[str, List[str]] - S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). - boto3_session : boto3.Session(), optional - Boto3 Session. The default boto3 session will be used if boto3_session receive None. - - Returns - ------- - torch.utils.data.Dataset - - Examples - -------- - >>> import awswrangler as wr - >>> import boto3 - >>> ds = wr.torch.AudioS3Dataset('s3://bucket/path', boto3.Session()) - - """ - super(AudioS3Dataset, self).__init__() - import torchaudio - - def parser_fn(self, obj): - waveform, sample_rate = torchaudio.load(obj) - return waveform, sample_rate - - -class LambdaS3Dataset(_BaseS3Dataset): - """PyTorch S3 Audio Dataset. - - Parameters - ---------- - path : Union[str, List[str]] - S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). - boto3_session : boto3.Session(), optional - Boto3 Session. The default boto3 session will be used if boto3_session receive None. - - Returns - ------- - torch.utils.data.Dataset - - Examples - -------- - >>> import awswrangler as wr - >>> import boto3 - >>> parse_fn = lambda x: torch.tensor(x) - >>> label_fn = lambda x: x.split('.')[-1] - >>> ds = wr.torch.LambdaS3Dataset('s3://bucket/path', boto3.Session(), parse_fn=parse_fn, label_fn=label_fn) - - """ - def __init__(self, parse_fn, label_fn): - self._parse_fn = parse_fn - self._label_fn = label_fn - - def label_fn(self, path): - return self._label_fn(path) - - def parse_fn(self, obj): - return self._parse_fn(obj) - - -class ImageS3Dataset(_S3PartitionedDataset): - - def __init__(self): - """PyTorch Image S3 Dataset. - - Assumes Images are stored with the following structure: - - bucket - ├── class=0 - │ ├── img0.jpeg - │ └── img1.jpeg - └── class=1 - ├── img2.jpeg - └── img3.jpeg - - Parameters - ---------- - path : Union[str, List[str]] - S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). - boto3_session : boto3.Session(), optional - Boto3 Session. The default boto3 session will be used if boto3_session receive None. - - Returns - ------- - torch.utils.data.Dataset - - Examples - -------- - >>> import awswrangler as wr - >>> import boto3 - >>> ds = wr.torch.ImageS3Dataset('s3://bucket/path', boto3.Session()) - - """ - super(ImageS3Dataset, self).__init__() - from PIL import Image - from torchvision.transforms.functional import to_tensor - - def parser_fn(self, obj): - image = Image.open(obj) - tensor = to_tensor(image) - tensor.unsqueeze_(0) - return tensor +# class AudioS3Dataset(_S3PartitionedDataset): +# +# def __init__(self): +# """PyTorch S3 Audio Dataset. +# +# Assumes audio files are stored with the following structure: +# +# bucket +# ├── class=0 +# │ ├── audio0.wav +# │ └── audio1.wav +# └── class=1 +# ├── audio2.wav +# └── audio3.wav +# +# Parameters +# ---------- +# path : Union[str, List[str]] +# S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). +# boto3_session : boto3.Session(), optional +# Boto3 Session. The default boto3 session will be used if boto3_session receive None. +# +# Returns +# ------- +# torch.utils.data.Dataset +# +# Examples +# -------- +# >>> import awswrangler as wr +# >>> import boto3 +# >>> ds = wr.torch.AudioS3Dataset('s3://bucket/path', boto3.Session()) +# +# """ +# super(AudioS3Dataset, self).__init__() +# import torchaudio +# +# def parser_fn(self, obj): +# waveform, sample_rate = torchaudio.load(obj) +# return waveform, sample_rate + + +# class LambdaS3Dataset(_BaseS3Dataset): +# """PyTorch S3 Audio Dataset. +# +# Parameters +# ---------- +# path : Union[str, List[str]] +# S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). +# boto3_session : boto3.Session(), optional +# Boto3 Session. The default boto3 session will be used if boto3_session receive None. +# +# Returns +# ------- +# torch.utils.data.Dataset +# +# Examples +# -------- +# >>> import awswrangler as wr +# >>> import boto3 +# >>> parse_fn = lambda x: torch.tensor(x) +# >>> label_fn = lambda x: x.split('.')[-1] +# >>> ds = wr.torch.LambdaS3Dataset('s3://bucket/path', boto3.Session(), parse_fn=parse_fn, label_fn=label_fn) +# +# """ +# def __init__(self, parse_fn, label_fn): +# self._parse_fn = parse_fn +# self._label_fn = label_fn +# +# def label_fn(self, path): +# return self._label_fn(path) +# +# def parse_fn(self, obj): +# return self._parse_fn(obj) +# +# +# class ImageS3Dataset(_S3PartitionedDataset): +# +# def __init__(self): +# """PyTorch Image S3 Dataset. +# +# Assumes Images are stored with the following structure: +# +# bucket +# ├── class=0 +# │ ├── img0.jpeg +# │ └── img1.jpeg +# └── class=1 +# ├── img2.jpeg +# └── img3.jpeg +# +# Parameters +# ---------- +# path : Union[str, List[str]] +# S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). +# boto3_session : boto3.Session(), optional +# Boto3 Session. The default boto3 session will be used if boto3_session receive None. +# +# Returns +# ------- +# torch.utils.data.Dataset +# +# Examples +# -------- +# >>> import awswrangler as wr +# >>> import boto3 +# >>> ds = wr.torch.ImageS3Dataset('s3://bucket/path', boto3.Session()) +# +# """ +# super(ImageS3Dataset, self).__init__() +# from PIL import Image +# from torchvision.transforms.functional import to_tensor +# +# def parser_fn(self, obj): +# image = Image.open(obj) +# tensor = to_tensor(image) +# tensor.unsqueeze_(0) +# return tensor class SQLDataset(IterableDataset): # pylint: disable=too-few-public-methods,abstract-method """Pytorch Iterable SQL Dataset.""" - def __init__(self, sql: str, con: sqlalchemy.engine.Engine, label_col: Optional[str], chunksize: Optional[int] = None,): + def __init__( + self, + sql: str, + con: sqlalchemy.engine.Engine, + label_col: Optional[Union[int, str]] = None, + chunksize: Optional[int] = None, + ): """Pytorch Iterable SQL Dataset. Support for **Redshift**, **PostgreSQL** and **MySQL**. @@ -205,6 +210,8 @@ def __init__(self, sql: str, con: sqlalchemy.engine.Engine, label_col: Optional[ con : sqlalchemy.engine.Engine SQLAlchemy Engine. Please use, wr.db.get_engine(), wr.db.get_redshift_temp_engine() or wr.catalog.get_engine() + label_col : int, optional + Label column number Returns ------- @@ -218,21 +225,53 @@ def __init__(self, sql: str, con: sqlalchemy.engine.Engine, label_col: Optional[ """ super().__init__() - self.sql = sql - self.con = con - self.label_col = label_col - self.chunksize = chunksize + self._sql = sql + self._con = con + self._label_col = label_col + self._chunksize = chunksize - def __iter__(self): + def __iter__(self) -> Union[Iterator[torch.Tensor], Iterator[Tuple[torch.Tensor, torch.Tensor]]]: """Iterate over the Dataset.""" - worker_info = torch.utils.data.get_worker_info() - if worker_info is None: # single-process data loading, return the full iterator - pass - else: # in a worker process + if torch.utils.data.get_worker_info() is not None: # type: ignore raise NotImplementedError() - ret = db._read_sql_query(fn=db._records2numpy, sql=self.sql, con=self.con, chunksize=self.chunksize) - if isinstance(ret, np.ndarray): - ret = [ret] - for ds in ret: - for row in ds: - yield torch.as_tensor(row, dtype=torch.float) + db._validate_engine(con=self._con) + with self._con.connect() as con: + cursor: Any = con.execute(self._sql) + if (self._label_col is not None) and isinstance(self._label_col, str): + label_col: Optional[int] = list(cursor.keys()).index(self._label_col) + else: + label_col = self._label_col + _logger.debug(f"label_col: {label_col}") + return self._records2tensor(cursor=cursor, chunksize=self._chunksize, label_col=label_col) + + @staticmethod + def _records2tensor( + cursor: Any, chunksize: Optional[int] = None, label_col: Optional[int] = None + ) -> Union[Iterator[torch.Tensor], Iterator[Tuple[torch.Tensor, torch.Tensor]]]: # pylint: disable=unused-argument + chunks: Iterator[Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]] + if chunksize is None: + chunks = iter([SQLDataset._records2numpy(records=cursor.fetchall(), label_col=label_col)]) + else: + chunks = db._iterate_cursor( # pylint: disable=protected-access + fn=SQLDataset._records2numpy, cursor=cursor, chunksize=chunksize, label_col=label_col + ) + if label_col is None: + for data in chunks: + for data_row in data: + yield torch.as_tensor(data_row, dtype=torch.float) # pylint: disable=no-member + for data, label in chunks: + for data_row, label_row in zip(data, label): + ts_data: torch.Tensor = torch.as_tensor(data_row, dtype=torch.float) # pylint: disable=no-member + ts_label: torch.Tensor = torch.as_tensor(label_row, dtype=torch.float) # pylint: disable=no-member + yield ts_data, ts_label + + @staticmethod + def _records2numpy( + records: List[Tuple[Any]], label_col: Optional[int] = None + ) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]: # pylint: disable=unused-argument + arr: np.ndarray = np.array(records, dtype=np.float) + if label_col is None: + return arr + data: np.ndarray = np.concatenate([arr[:, :label_col], arr[:, (label_col + 1) :]], axis=1) # noqa: E203 + label: np.ndarray = arr[:, label_col] + return data, label diff --git a/testing/test_awswrangler/test_torch.py b/testing/test_awswrangler/test_torch.py index f30736c16..d39ec8ddb 100644 --- a/testing/test_awswrangler/test_torch.py +++ b/testing/test_awswrangler/test_torch.py @@ -52,14 +52,10 @@ def parameters(cloudformation_outputs): yield parameters -@pytest.mark.parametrize("db_type, chunksize", [ - ("mysql", None), - ("redshift", None), - ("postgresql", None), - ("mysql", 1), - ("redshift", 1), - ("postgresql", 1), -]) +@pytest.mark.parametrize( + "db_type, chunksize", + [("mysql", None), ("redshift", None), ("postgresql", None), ("mysql", 1), ("redshift", 1), ("postgresql", 1)], +) def test_torch_sql(parameters, db_type, chunksize): schema = parameters[db_type]["schema"] table = "test_torch_sql" @@ -73,7 +69,7 @@ def test_torch_sql(parameters, db_type, chunksize): index=False, index_label=None, chunksize=None, - method=None + method=None, ) ds = list(wr.torch.SQLDataset(f"SELECT * FROM {schema}.{table}", con=engine, chunksize=chunksize)) assert torch.all(ds[0].eq(torch.tensor([1.0, 4.0]))) @@ -81,14 +77,38 @@ def test_torch_sql(parameters, db_type, chunksize): assert torch.all(ds[2].eq(torch.tensor([3.0, 6.0]))) +@pytest.mark.parametrize( + "db_type, chunksize", + [("mysql", None), ("redshift", None), ("postgresql", None), ("mysql", 1), ("redshift", 1), ("postgresql", 1)], +) +def test_torch_sql_label(parameters, db_type, chunksize): + schema = parameters[db_type]["schema"] + table = "test_torch_sql_label" + engine = wr.catalog.get_engine(connection=f"aws-data-wrangler-{db_type}") + wr.db.to_sql( + df=pd.DataFrame({"a": [1.0, 2.0, 3.0], "b": [4.0, 5.0, 6.0], "c": [7, 8, 9]}), + con=engine, + name=table, + schema=schema, + if_exists="replace", + index=False, + index_label=None, + chunksize=None, + method=None, + ) + ts = list(wr.torch.SQLDataset(f"SELECT * FROM {schema}.{table}", con=engine, chunksize=chunksize, label_col=2)) + assert torch.all(ts[0][0].eq(torch.tensor([1.0, 4.0]))) + assert torch.all(ts[0][1].eq(torch.tensor([7], dtype=torch.long))) + assert torch.all(ts[1][0].eq(torch.tensor([2.0, 5.0]))) + assert torch.all(ts[1][1].eq(torch.tensor([8], dtype=torch.long))) + assert torch.all(ts[2][0].eq(torch.tensor([3.0, 6.0]))) + assert torch.all(ts[2][1].eq(torch.tensor([9], dtype=torch.long))) + + def test_torch_image_s3(bucket): - s3 = boto3.client('s3') + s3 = boto3.client("s3") ref_label = 0 - s3.put_object( - Body=open("../../docs/source/_static/logo.png"), - Bucket=bucket, - Key=f'class={ref_label}/logo.png', - ) + s3.put_object(Body=open("../../docs/source/_static/logo.png"), Bucket=bucket, Key=f"class={ref_label}/logo.png") ds = wr.torch.ImageS3Dataset() for image, label in ds: assert image.shape == torch.Size([1, 28, 28]) @@ -100,4 +120,4 @@ def test_torch_image_s3(bucket): # ds = wr.torch.AudioS3Dataset() # for image, label in ds: # assert image.shape == torch.Size([1, 28, 28]) -# break \ No newline at end of file +# break From bf1be0746d0523d91db1d9181152150ff18c9919 Mon Sep 17 00:00:00 2001 From: igorborgest Date: Mon, 20 Apr 2020 09:20:41 -0300 Subject: [PATCH 07/27] Updating catersian product of pytest parameters --- testing/test_awswrangler/test_torch.py | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/testing/test_awswrangler/test_torch.py b/testing/test_awswrangler/test_torch.py index d39ec8ddb..3c08ec319 100644 --- a/testing/test_awswrangler/test_torch.py +++ b/testing/test_awswrangler/test_torch.py @@ -52,10 +52,8 @@ def parameters(cloudformation_outputs): yield parameters -@pytest.mark.parametrize( - "db_type, chunksize", - [("mysql", None), ("redshift", None), ("postgresql", None), ("mysql", 1), ("redshift", 1), ("postgresql", 1)], -) +@pytest.mark.parametrize("chunksize", [None, 1, 10]) +@pytest.mark.parametrize("db_type", ["mysql", "redshift", "postgresql"]) def test_torch_sql(parameters, db_type, chunksize): schema = parameters[db_type]["schema"] table = "test_torch_sql" @@ -77,10 +75,8 @@ def test_torch_sql(parameters, db_type, chunksize): assert torch.all(ds[2].eq(torch.tensor([3.0, 6.0]))) -@pytest.mark.parametrize( - "db_type, chunksize", - [("mysql", None), ("redshift", None), ("postgresql", None), ("mysql", 1), ("redshift", 1), ("postgresql", 1)], -) +@pytest.mark.parametrize("chunksize", [None, 1, 10]) +@pytest.mark.parametrize("db_type", ["mysql", "redshift", "postgresql"]) def test_torch_sql_label(parameters, db_type, chunksize): schema = parameters[db_type]["schema"] table = "test_torch_sql_label" From 1a41d1887217312298f2fab4f32e156fffb7e8d5 Mon Sep 17 00:00:00 2001 From: igorborgest Date: Mon, 20 Apr 2020 12:37:21 -0300 Subject: [PATCH 08/27] Pivoting SQLDataset parser strategy to avoid cast losses. --- awswrangler/db.py | 14 +- awswrangler/torch.py | 169 ++++++++++++------------- testing/test_awswrangler/test_torch.py | 18 +-- 3 files changed, 100 insertions(+), 101 deletions(-) diff --git a/awswrangler/db.py b/awswrangler/db.py index e69739433..5d16301ad 100644 --- a/awswrangler/db.py +++ b/awswrangler/db.py @@ -2,7 +2,7 @@ import json import logging -from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union +from typing import Any, Dict, Iterator, List, Optional, Tuple, Union from urllib.parse import quote_plus import boto3 # type: ignore @@ -162,7 +162,7 @@ def read_sql_query( if chunksize is None: return _records2df(records=cursor.fetchall(), cols_names=cursor.keys(), index=index_col, dtype=dtype) return _iterate_cursor( - fn=_records2df, cursor=cursor, chunksize=chunksize, cols_names=cursor.keys(), index=index_col, dtype=dtype + cursor=cursor, chunksize=chunksize, cols_names=cursor.keys(), index=index_col, dtype=dtype ) @@ -193,12 +193,18 @@ def _records2df( return df -def _iterate_cursor(fn: Callable, cursor: Any, chunksize: int, **kwargs) -> Iterator[Any]: +def _iterate_cursor( + cursor: Any, + chunksize: int, + cols_names: List[str], + index: Optional[Union[str, List[str]]], + dtype: Optional[Dict[str, pa.DataType]] = None, +) -> Iterator[pd.DataFrame]: while True: records = cursor.fetchmany(chunksize) if not records: break - yield fn(records=records, **kwargs) + yield _records2df(records=records, cols_names=cols_names, index=index, dtype=dtype) def _convert_params(sql: str, params: Optional[Union[List, Tuple, Dict]]) -> List[Any]: diff --git a/awswrangler/torch.py b/awswrangler/torch.py index b27422750..a73f4d198 100644 --- a/awswrangler/torch.py +++ b/awswrangler/torch.py @@ -1,79 +1,75 @@ """PyTorch Module.""" -import re import logging -from io import BytesIO +# import re +# from io import BytesIO from typing import Any, Iterator, List, Optional, Tuple, Union +# import boto3 # type: ignore import numpy as np # type: ignore import sqlalchemy # type: ignore -import boto3 # type: ignore import torch -from torch.utils.data.dataset import Dataset, IterableDataset +from torch.utils.data.dataset import IterableDataset -from awswrangler import db, _utils, s3 +from awswrangler import db # , s3, _utils _logger: logging.Logger = logging.getLogger(__name__) -class _BaseS3Dataset(Dataset): - """PyTorch Map-Style S3 Dataset.""" - - def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session): - """PyTorch Map-Style S3 Dataset. - - Parameters - ---------- - path : Union[str, List[str]] - S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). - boto3_session : boto3.Session(), optional - Boto3 Session. The default boto3 session will be used if boto3_session receive None. - - Returns - ------- - torch.utils.data.Dataset - - """ - super().__init__() - self.session = _utils.ensure_session(session=boto3_session) - self.paths: List[str] = s3._path2list( - path=path, - suffix=suffix, - boto3_session=self.session, - ) - - def __getitem__(self, index): - path = self.paths[index] - obj = self._fetch_obj(path) - return [self.parser_fn(obj), self.label_fn(path)] - - def __len__(self): - return len(self.paths) - - def _fetch_obj(self, path): - bucket, key = _utils.parse_path(path=path) - buff = BytesIO() - client_s3: boto3.client = _utils.client(service_name="s3", session=self.session) - client_s3.download_fileobj(Bucket=bucket, Key=key, Fileobj=buff) - return buff.seek(0) - - def parser_fn(self, obj): - pass - - def label_fn(self, path): - pass - - -class _S3PartitionedDataset(_BaseS3Dataset): - - def label_fn(self, path): - return int(re.findall(r'/(.*?)=(.*?)/', path)[-1][1]) +# class _BaseS3Dataset(Dataset): +# """PyTorch Map-Style S3 Dataset.""" +# +# def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session): +# """Pytorch Map-Style S3 Dataset. +# +# Parameters +# ---------- +# path : Union[str, List[str]] +# S3 prefix (e.g. s3://bucket/prefix) +# or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). +# boto3_session : boto3.Session(), optional +# Boto3 Session. The default boto3 session will be used if boto3_session receive None. +# +# Returns +# ------- +# torch.utils.data.Dataset +# +# """ +# super().__init__() +# self.session = _utils.ensure_session(session=boto3_session) +# self.paths: List[str] = s3._path2list(path=path, suffix=suffix, boto3_session=self.session) +# +# def __getitem__(self, index): +# path = self.paths[index] +# obj = self._fetch_obj(path) +# return [self.parser_fn(obj), self.label_fn(path)] +# +# def __len__(self): +# return len(self.paths) +# +# def _fetch_obj(self, path): +# bucket, key = _utils.parse_path(path=path) +# buff = BytesIO() +# client_s3: boto3.client = _utils.client(service_name="s3", session=self.session) +# client_s3.download_fileobj(Bucket=bucket, Key=key, Fileobj=buff) +# return buff.seek(0) +# +# def parser_fn(self, obj): +# pass +# +# def label_fn(self, path): +# pass +# +# +# class _S3PartitionedDataset(_BaseS3Dataset): +# def label_fn(self, path): +# return int(re.findall(r"/(.*?)=(.*?)/", path)[-1][1]) # class AudioS3Dataset(_S3PartitionedDataset): # # def __init__(self): -# """PyTorch S3 Audio Dataset. +# """Pytorch S3 Audio Dataset. # # Assumes audio files are stored with the following structure: # @@ -88,7 +84,8 @@ def label_fn(self, path): # Parameters # ---------- # path : Union[str, List[str]] -# S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). +# S3 prefix (e.g. s3://bucket/prefix) +# or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). # boto3_session : boto3.Session(), optional # Boto3 Session. The default boto3 session will be used if boto3_session receive None. # @@ -163,7 +160,8 @@ def label_fn(self, path): # Parameters # ---------- # path : Union[str, List[str]] -# S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). +# S3 prefix (e.g. s3://bucket/prefix) +# or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). # boto3_session : boto3.Session(), optional # Boto3 Session. The default boto3 session will be used if boto3_session receive None. # @@ -242,36 +240,31 @@ def __iter__(self) -> Union[Iterator[torch.Tensor], Iterator[Tuple[torch.Tensor, else: label_col = self._label_col _logger.debug(f"label_col: {label_col}") - return self._records2tensor(cursor=cursor, chunksize=self._chunksize, label_col=label_col) + if self._chunksize is None: + return SQLDataset._records2tensor(records=cursor.fetchall(), label_col=label_col) + return self._iterate_cursor(cursor=cursor, chunksize=self._chunksize, label_col=label_col) @staticmethod - def _records2tensor( - cursor: Any, chunksize: Optional[int] = None, label_col: Optional[int] = None - ) -> Union[Iterator[torch.Tensor], Iterator[Tuple[torch.Tensor, torch.Tensor]]]: # pylint: disable=unused-argument - chunks: Iterator[Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]] - if chunksize is None: - chunks = iter([SQLDataset._records2numpy(records=cursor.fetchall(), label_col=label_col)]) - else: - chunks = db._iterate_cursor( # pylint: disable=protected-access - fn=SQLDataset._records2numpy, cursor=cursor, chunksize=chunksize, label_col=label_col - ) - if label_col is None: - for data in chunks: - for data_row in data: - yield torch.as_tensor(data_row, dtype=torch.float) # pylint: disable=no-member - for data, label in chunks: - for data_row, label_row in zip(data, label): - ts_data: torch.Tensor = torch.as_tensor(data_row, dtype=torch.float) # pylint: disable=no-member - ts_label: torch.Tensor = torch.as_tensor(label_row, dtype=torch.float) # pylint: disable=no-member - yield ts_data, ts_label + def _iterate_cursor( + cursor: Any, chunksize: int, label_col: Optional[int] = None + ) -> Union[Iterator[torch.Tensor], Iterator[Tuple[torch.Tensor, torch.Tensor]]]: + while True: + records = cursor.fetchmany(chunksize) + if not records: + break + yield from SQLDataset._records2tensor(records=records, label_col=label_col) @staticmethod - def _records2numpy( + def _records2tensor( records: List[Tuple[Any]], label_col: Optional[int] = None - ) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]: # pylint: disable=unused-argument - arr: np.ndarray = np.array(records, dtype=np.float) - if label_col is None: - return arr - data: np.ndarray = np.concatenate([arr[:, :label_col], arr[:, (label_col + 1) :]], axis=1) # noqa: E203 - label: np.ndarray = arr[:, label_col] - return data, label + ) -> Union[Iterator[torch.Tensor], Iterator[Tuple[torch.Tensor, torch.Tensor]]]: # pylint: disable=unused-argument + for row in records: + if label_col is None: + arr_data: np.ndarray = np.array(row, dtype=np.float) + yield torch.as_tensor(arr_data, dtype=torch.float) # pylint: disable=no-member + else: + arr_data = np.array(row[:label_col] + row[label_col + 1 :], dtype=np.float) # noqa: E203 + arr_label: np.ndarray = np.array(row[label_col], dtype=np.long) + ts_data: torch.Tensor = torch.as_tensor(arr_data, dtype=torch.float) # pylint: disable=no-member + ts_label: torch.Tensor = torch.as_tensor(arr_label, dtype=torch.long) # pylint: disable=no-member + yield ts_data, ts_label diff --git a/testing/test_awswrangler/test_torch.py b/testing/test_awswrangler/test_torch.py index 3c08ec319..456269244 100644 --- a/testing/test_awswrangler/test_torch.py +++ b/testing/test_awswrangler/test_torch.py @@ -101,15 +101,15 @@ def test_torch_sql_label(parameters, db_type, chunksize): assert torch.all(ts[2][1].eq(torch.tensor([9], dtype=torch.long))) -def test_torch_image_s3(bucket): - s3 = boto3.client("s3") - ref_label = 0 - s3.put_object(Body=open("../../docs/source/_static/logo.png"), Bucket=bucket, Key=f"class={ref_label}/logo.png") - ds = wr.torch.ImageS3Dataset() - for image, label in ds: - assert image.shape == torch.Size([1, 28, 28]) - assert label == torch.int(ref_label) - break +# def test_torch_image_s3(bucket): +# s3 = boto3.client("s3") +# ref_label = 0 +# s3.put_object(Body=open("../../docs/source/_static/logo.png"), Bucket=bucket, Key=f"class={ref_label}/logo.png") +# ds = wr.torch.ImageS3Dataset() +# for image, label in ds: +# assert image.shape == torch.Size([1, 28, 28]) +# assert label == torch.int(ref_label) +# break # def test_torch_audio_s3(bucket): From 36c15e48d6afbd9925f2f57f495c82c39ef16171 Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Mon, 20 Apr 2020 15:05:09 -0300 Subject: [PATCH 09/27] tested lambda & image datasets --- awswrangler/torch.py | 359 +++++++++++++------------ testing/test_awswrangler/test_torch.py | 82 +++++- 2 files changed, 255 insertions(+), 186 deletions(-) diff --git a/awswrangler/torch.py b/awswrangler/torch.py index a73f4d198..d797193e8 100644 --- a/awswrangler/torch.py +++ b/awswrangler/torch.py @@ -1,190 +1,195 @@ """PyTorch Module.""" +import re import logging -# import re -# from io import BytesIO -from typing import Any, Iterator, List, Optional, Tuple, Union -# import boto3 # type: ignore +import torch # type: ignore +import boto3 # type: ignore import numpy as np # type: ignore import sqlalchemy # type: ignore -import torch -from torch.utils.data.dataset import IterableDataset -from awswrangler import db # , s3, _utils +from PIL import Image +from io import BytesIO +from typing import Any, Iterator, List, Optional, Tuple, Union, Callable +from torch.utils.data.dataset import Dataset, IterableDataset +from torchvision.transforms.functional import to_tensor + +from awswrangler import db, s3, _utils _logger: logging.Logger = logging.getLogger(__name__) -# class _BaseS3Dataset(Dataset): -# """PyTorch Map-Style S3 Dataset.""" -# -# def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session): -# """Pytorch Map-Style S3 Dataset. -# -# Parameters -# ---------- -# path : Union[str, List[str]] -# S3 prefix (e.g. s3://bucket/prefix) -# or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). -# boto3_session : boto3.Session(), optional -# Boto3 Session. The default boto3 session will be used if boto3_session receive None. -# -# Returns -# ------- -# torch.utils.data.Dataset -# -# """ -# super().__init__() -# self.session = _utils.ensure_session(session=boto3_session) -# self.paths: List[str] = s3._path2list(path=path, suffix=suffix, boto3_session=self.session) -# -# def __getitem__(self, index): -# path = self.paths[index] -# obj = self._fetch_obj(path) -# return [self.parser_fn(obj), self.label_fn(path)] -# -# def __len__(self): -# return len(self.paths) -# -# def _fetch_obj(self, path): -# bucket, key = _utils.parse_path(path=path) -# buff = BytesIO() -# client_s3: boto3.client = _utils.client(service_name="s3", session=self.session) -# client_s3.download_fileobj(Bucket=bucket, Key=key, Fileobj=buff) -# return buff.seek(0) -# -# def parser_fn(self, obj): -# pass -# -# def label_fn(self, path): -# pass -# -# -# class _S3PartitionedDataset(_BaseS3Dataset): -# def label_fn(self, path): -# return int(re.findall(r"/(.*?)=(.*?)/", path)[-1][1]) - - -# class AudioS3Dataset(_S3PartitionedDataset): -# -# def __init__(self): -# """Pytorch S3 Audio Dataset. -# -# Assumes audio files are stored with the following structure: -# -# bucket -# ├── class=0 -# │ ├── audio0.wav -# │ └── audio1.wav -# └── class=1 -# ├── audio2.wav -# └── audio3.wav -# -# Parameters -# ---------- -# path : Union[str, List[str]] -# S3 prefix (e.g. s3://bucket/prefix) -# or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). -# boto3_session : boto3.Session(), optional -# Boto3 Session. The default boto3 session will be used if boto3_session receive None. -# -# Returns -# ------- -# torch.utils.data.Dataset -# -# Examples -# -------- -# >>> import awswrangler as wr -# >>> import boto3 -# >>> ds = wr.torch.AudioS3Dataset('s3://bucket/path', boto3.Session()) -# -# """ -# super(AudioS3Dataset, self).__init__() -# import torchaudio -# -# def parser_fn(self, obj): -# waveform, sample_rate = torchaudio.load(obj) -# return waveform, sample_rate - - -# class LambdaS3Dataset(_BaseS3Dataset): -# """PyTorch S3 Audio Dataset. -# -# Parameters -# ---------- -# path : Union[str, List[str]] -# S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). -# boto3_session : boto3.Session(), optional -# Boto3 Session. The default boto3 session will be used if boto3_session receive None. -# -# Returns -# ------- -# torch.utils.data.Dataset -# -# Examples -# -------- -# >>> import awswrangler as wr -# >>> import boto3 -# >>> parse_fn = lambda x: torch.tensor(x) -# >>> label_fn = lambda x: x.split('.')[-1] -# >>> ds = wr.torch.LambdaS3Dataset('s3://bucket/path', boto3.Session(), parse_fn=parse_fn, label_fn=label_fn) -# -# """ -# def __init__(self, parse_fn, label_fn): -# self._parse_fn = parse_fn -# self._label_fn = label_fn -# -# def label_fn(self, path): -# return self._label_fn(path) -# -# def parse_fn(self, obj): -# return self._parse_fn(obj) -# -# -# class ImageS3Dataset(_S3PartitionedDataset): -# -# def __init__(self): -# """PyTorch Image S3 Dataset. -# -# Assumes Images are stored with the following structure: -# -# bucket -# ├── class=0 -# │ ├── img0.jpeg -# │ └── img1.jpeg -# └── class=1 -# ├── img2.jpeg -# └── img3.jpeg -# -# Parameters -# ---------- -# path : Union[str, List[str]] -# S3 prefix (e.g. s3://bucket/prefix) -# or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). -# boto3_session : boto3.Session(), optional -# Boto3 Session. The default boto3 session will be used if boto3_session receive None. -# -# Returns -# ------- -# torch.utils.data.Dataset -# -# Examples -# -------- -# >>> import awswrangler as wr -# >>> import boto3 -# >>> ds = wr.torch.ImageS3Dataset('s3://bucket/path', boto3.Session()) -# -# """ -# super(ImageS3Dataset, self).__init__() -# from PIL import Image -# from torchvision.transforms.functional import to_tensor -# -# def parser_fn(self, obj): -# image = Image.open(obj) -# tensor = to_tensor(image) -# tensor.unsqueeze_(0) -# return tensor +class _BaseS3Dataset(Dataset): + """PyTorch Map-Style S3 Dataset.""" + + def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session: boto3.Session): + """PyTorch Map-Style S3 Dataset. + + Parameters + ---------- + path : Union[str, List[str]] + S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + boto3_session : boto3.Session(), optional + Boto3 Session. The default boto3 session will be used if boto3_session receive None. + + Returns + ------- + torch.utils.data.Dataset + + """ + super().__init__() + self.session = _utils.ensure_session(session=boto3_session) + self.paths: List[str] = s3._path2list( # pylint: disable=protected-access + path=path, + suffix=suffix, + boto3_session=self.session, + ) + + def __getitem__(self, index): + path = self.paths[index] + data = self._fetch_data(path) + return [self.data_fn(data), self.label_fn(path)] + + def __len__(self): + return len(self.paths) + + def _fetch_data(self, path): + bucket, key = _utils.parse_path(path=path) + buff = BytesIO() + client_s3: boto3.client = _utils.client(service_name="s3", session=self.session) + client_s3.download_fileobj(Bucket=bucket, Key=key, Fileobj=buff) + buff.seek(0) + return buff + + def data_fn(self, obj): + pass + + def label_fn(self, path): + pass + + +class _S3PartitionedDataset(_BaseS3Dataset): + + def label_fn(self, path): + return int(re.findall(r'/(.*?)=(.*?)/', path)[-1][1]) + + +class LambdaS3Dataset(_BaseS3Dataset): + + def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session: boto3.Session, data_fn: Callable, label_fn: Callable): + """PyTorch S3 Audio Dataset. + + Parameters + ---------- + path : Union[str, List[str]] + S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + boto3_session : boto3.Session(), optional + Boto3 Session. The default boto3 session will be used if boto3_session receive None. + + Returns + ------- + torch.utils.data.Dataset + + Examples + -------- + >>> import awswrangler as wr + >>> import boto3 + >>> data_fn = lambda x: torch.tensor(x) + >>> label_fn = lambda x: x.split('.')[-1] + >>> ds = wr.torch.LambdaS3Dataset('s3://bucket/path', boto3.Session(), data_fn=data_fn, label_fn=label_fn) + + """ + super(LambdaS3Dataset, self).__init__(path, suffix, boto3_session) + self._data_fn = data_fn + self._label_fn = label_fn + + def label_fn(self, path): + return self._label_fn(path) + + def data_fn(self, data): + print(type(data), data) + return self._data_fn(data) + + +class AudioS3Dataset(_S3PartitionedDataset): + + def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session: boto3.Session): + """PyTorch S3 Audio Dataset. + + Assumes audio files are stored with the following structure: + + bucket + ├── class=0 + │ ├── audio0.wav + │ └── audio1.wav + └── class=1 + ├── audio2.wav + └── audio3.wav + + Parameters + ---------- + path : Union[str, List[str]] + S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + boto3_session : boto3.Session(), optional + Boto3 Session. The default boto3 session will be used if boto3_session receive None. + + Returns + ------- + torch.utils.data.Dataset + + Examples + -------- + >>> import awswrangler as wr + >>> import boto3 + >>> ds = wr.torch.AudioS3Dataset('s3://bucket/path', boto3.Session()) + + """ + super(AudioS3Dataset, self).__init__(path, suffix, boto3_session) + + def data_fn(self, data): + waveform, sample_rate = torchaudio.load(data) + return waveform, sample_rate + + +class ImageS3Dataset(_S3PartitionedDataset): + + def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session: boto3.Session): + """PyTorch Image S3 Dataset. + + Assumes Images are stored with the following structure: + + bucket + ├── class=0 + │ ├── img0.jpeg + │ └── img1.jpeg + └── class=1 + ├── img2.jpeg + └── img3.jpeg + + Parameters + ---------- + path : Union[str, List[str]] + S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + boto3_session : boto3.Session(), optional + Boto3 Session. The default boto3 session will be used if boto3_session receive None. + + Returns + ------- + torch.utils.data.Dataset + + Examples + -------- + >>> import awswrangler as wr + >>> import boto3 + >>> ds = wr.torch.ImageS3Dataset('s3://bucket/path', boto3.Session()) + + """ + super(ImageS3Dataset, self).__init__(path, suffix, boto3_session) + + def data_fn(self, data): + image = Image.open(data) + tensor = to_tensor(image) + return tensor class SQLDataset(IterableDataset): # pylint: disable=too-few-public-methods,abstract-method @@ -232,7 +237,7 @@ def __iter__(self) -> Union[Iterator[torch.Tensor], Iterator[Tuple[torch.Tensor, """Iterate over the Dataset.""" if torch.utils.data.get_worker_info() is not None: # type: ignore raise NotImplementedError() - db._validate_engine(con=self._con) + db._validate_engine(con=self._con) # pylint: disable=protected-access with self._con.connect() as con: cursor: Any = con.execute(self._sql) if (self._label_col is not None) and isinstance(self._label_col, str): diff --git a/testing/test_awswrangler/test_torch.py b/testing/test_awswrangler/test_torch.py index 456269244..4f508b31c 100644 --- a/testing/test_awswrangler/test_torch.py +++ b/testing/test_awswrangler/test_torch.py @@ -1,10 +1,16 @@ import logging +import re import boto3 +import numpy as np import pandas as pd import pytest import torch +from PIL import Image +from torch.utils.data import DataLoader +from torchvision.transforms.functional import to_tensor + import awswrangler as wr logging.basicConfig(level=logging.INFO, format="[%(asctime)s][%(levelname)s][%(name)s][%(funcName)s] %(message)s") @@ -101,16 +107,74 @@ def test_torch_sql_label(parameters, db_type, chunksize): assert torch.all(ts[2][1].eq(torch.tensor([9], dtype=torch.long))) -# def test_torch_image_s3(bucket): -# s3 = boto3.client("s3") -# ref_label = 0 -# s3.put_object(Body=open("../../docs/source/_static/logo.png"), Bucket=bucket, Key=f"class={ref_label}/logo.png") -# ds = wr.torch.ImageS3Dataset() -# for image, label in ds: -# assert image.shape == torch.Size([1, 28, 28]) -# assert label == torch.int(ref_label) -# break +def test_torch_image_s3(bucket): + wr.s3.delete_objects(path=bucket, boto3_session=boto3.Session()) + + s3 = boto3.client("s3") + ref_label = 0 + s3.put_object( + Body=open("../../docs/source/_static/logo.png", "rb").read(), + Bucket=bucket, + Key=f"class={ref_label}/logo.png", + ContentType="image/png", + ) + ds = wr.torch.ImageS3Dataset(path=bucket, suffix="png", boto3_session=boto3.Session()) + image, label = ds[0] + assert image.shape == torch.Size([4, 494, 1636]) + assert label == torch.tensor(ref_label, dtype=torch.int) + + wr.s3.delete_objects(path=bucket, boto3_session=boto3.Session()) + + +def test_torch_image_s3_dataloader(bucket): + wr.s3.delete_objects(path=bucket, boto3_session=boto3.Session()) + + s3 = boto3.client("s3") + labels = np.random.randint(0, 4, size=(8,)) + for i, label in enumerate(labels): + s3.put_object( + Body=open("../../docs/source/_static/logo.png", "rb").read(), + Bucket=bucket, + Key=f"class={label}/logo{i}.png", + ContentType="image/png", + ) + ds = wr.torch.ImageS3Dataset(path=bucket, suffix="png", boto3_session=boto3.Session()) + batch_size = 2 + num_train = len(ds) + indices = list(range(num_train)) + loader = DataLoader( + ds, batch_size=batch_size, num_workers=4, sampler=torch.utils.data.sampler.RandomSampler(indices) + ) + for i, (image, label) in enumerate(loader): + assert image.shape == torch.Size([batch_size, 4, 494, 1636]) + assert label.dtype == torch.int64 + + wr.s3.delete_objects(path=bucket, boto3_session=boto3.Session()) + + +def test_torch_lambda_s3(bucket): + wr.s3.delete_objects(path=bucket, boto3_session=boto3.Session()) + + s3 = boto3.client("s3") + ref_label = 0 + s3.put_object( + Body=open("../../docs/source/_static/logo.png", "rb").read(), + Bucket=bucket, + Key=f"class={ref_label}/logo.png", + ContentType="image/png", + ) + ds = wr.torch.LambdaS3Dataset( + path=bucket, + suffix="png", + boto3_session=boto3.Session(), + data_fn=lambda x: to_tensor(Image.open(x)), + label_fn=lambda x: int(re.findall(r'/class=(.*?)/', x)[-1]), + ) + image, label = ds[0] + assert image.shape == torch.Size([4, 494, 1636]) + assert label == torch.tensor(ref_label, dtype=torch.int) + wr.s3.delete_objects(path=bucket, boto3_session=boto3.Session()) # def test_torch_audio_s3(bucket): # ds = wr.torch.AudioS3Dataset() From d4dcfc521f1f6cc8c0fdf1de485a7c29b8667cae Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Mon, 20 Apr 2020 15:35:11 -0300 Subject: [PATCH 10/27] add audio test --- awswrangler/torch.py | 3 ++- testing/test_awswrangler/test_torch.py | 29 +++++++++++++++++++------- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/awswrangler/torch.py b/awswrangler/torch.py index d797193e8..4a6a76567 100644 --- a/awswrangler/torch.py +++ b/awswrangler/torch.py @@ -1,5 +1,4 @@ """PyTorch Module.""" - import re import logging @@ -7,6 +6,7 @@ import boto3 # type: ignore import numpy as np # type: ignore import sqlalchemy # type: ignore +import torchaudio from PIL import Image from io import BytesIO @@ -147,6 +147,7 @@ def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session: boto super(AudioS3Dataset, self).__init__(path, suffix, boto3_session) def data_fn(self, data): + waveform, sample_rate = torchaudio.load(data) return waveform, sample_rate diff --git a/testing/test_awswrangler/test_torch.py b/testing/test_awswrangler/test_torch.py index 4f508b31c..a54797440 100644 --- a/testing/test_awswrangler/test_torch.py +++ b/testing/test_awswrangler/test_torch.py @@ -138,12 +138,19 @@ def test_torch_image_s3_dataloader(bucket): Key=f"class={label}/logo{i}.png", ContentType="image/png", ) - ds = wr.torch.ImageS3Dataset(path=bucket, suffix="png", boto3_session=boto3.Session()) + ds = wr.torch.ImageS3Dataset( + path=bucket, + suffix="png", + boto3_session=boto3.Session(), + ) batch_size = 2 num_train = len(ds) indices = list(range(num_train)) loader = DataLoader( - ds, batch_size=batch_size, num_workers=4, sampler=torch.utils.data.sampler.RandomSampler(indices) + ds, + batch_size=batch_size, + num_workers=4, + sampler=torch.utils.data.sampler.RandomSampler(indices), ) for i, (image, label) in enumerate(loader): assert image.shape == torch.Size([batch_size, 4, 494, 1636]) @@ -176,8 +183,16 @@ def test_torch_lambda_s3(bucket): wr.s3.delete_objects(path=bucket, boto3_session=boto3.Session()) -# def test_torch_audio_s3(bucket): -# ds = wr.torch.AudioS3Dataset() -# for image, label in ds: -# assert image.shape == torch.Size([1, 28, 28]) -# break + +def test_torch_audio_s3(bucket): + ds = wr.torch.AudioS3Dataset( + path="s3://multimedia-commons/data/videos/mp4/006/039/006039642c984a788569c7fea33ef3.mp4", + suffix="png", + boto3_session=boto3.Session(), + ) + loader = DataLoader( + ds, + batch_size=1, + ) + for image, label in loader: + assert image.shape == torch.Size([1, 28, 28]) From 30dc2fa5b275c04b5d94dc9799e9653ab479f65e Mon Sep 17 00:00:00 2001 From: igorborgest Date: Mon, 20 Apr 2020 18:22:50 -0300 Subject: [PATCH 11/27] Add test for torch.AudioS3Dataset --- .pylintrc | 3 +- awswrangler/torch.py | 111 +++++++++++++++---------- pytest.ini | 2 +- requirements-dev.txt | 3 +- testing/run-validations.sh | 2 +- testing/test_awswrangler/test_torch.py | 82 +++++++++--------- 6 files changed, 114 insertions(+), 89 deletions(-) diff --git a/.pylintrc b/.pylintrc index 132ce213a..4f41cb3fb 100644 --- a/.pylintrc +++ b/.pylintrc @@ -141,7 +141,8 @@ disable=print-statement, comprehension-escape, C0330, C0103, - W1202 + W1202, + too-few-public-methods # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option diff --git a/awswrangler/torch.py b/awswrangler/torch.py index 4a6a76567..db09abc46 100644 --- a/awswrangler/torch.py +++ b/awswrangler/torch.py @@ -1,20 +1,21 @@ """PyTorch Module.""" -import re import logging +import os +import pathlib +import re +from io import BytesIO +from typing import Any, Callable, Iterator, List, Optional, Tuple, Union -import torch # type: ignore import boto3 # type: ignore import numpy as np # type: ignore import sqlalchemy # type: ignore -import torchaudio - -from PIL import Image -from io import BytesIO -from typing import Any, Iterator, List, Optional, Tuple, Union, Callable -from torch.utils.data.dataset import Dataset, IterableDataset -from torchvision.transforms.functional import to_tensor +import torch # type: ignore +import torchaudio # type: ignore +from PIL import Image # type: ignore +from torch.utils.data.dataset import Dataset, IterableDataset # type: ignore +from torchvision.transforms.functional import to_tensor # type: ignore -from awswrangler import db, s3, _utils +from awswrangler import _utils, db, s3 _logger: logging.Logger = logging.getLogger(__name__) @@ -22,7 +23,9 @@ class _BaseS3Dataset(Dataset): """PyTorch Map-Style S3 Dataset.""" - def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session: boto3.Session): + def __init__( + self, path: Union[str, List[str]], suffix: Optional[str] = None, boto3_session: Optional[boto3.Session] = None + ): """PyTorch Map-Style S3 Dataset. Parameters @@ -38,46 +41,51 @@ def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session: boto """ super().__init__() - self.session = _utils.ensure_session(session=boto3_session) - self.paths: List[str] = s3._path2list( # pylint: disable=protected-access - path=path, - suffix=suffix, - boto3_session=self.session, + self._session = _utils.ensure_session(session=boto3_session) + self._paths: List[str] = s3._path2list( # pylint: disable=protected-access + path=path, suffix=suffix, boto3_session=self._session ) def __getitem__(self, index): - path = self.paths[index] + path = self._paths[index] data = self._fetch_data(path) - return [self.data_fn(data), self.label_fn(path)] + return [self._data_fn(data), self._label_fn(path)] def __len__(self): - return len(self.paths) + return len(self._paths) def _fetch_data(self, path): bucket, key = _utils.parse_path(path=path) buff = BytesIO() - client_s3: boto3.client = _utils.client(service_name="s3", session=self.session) + client_s3: boto3.client = _utils.client(service_name="s3", session=self._session) client_s3.download_fileobj(Bucket=bucket, Key=key, Fileobj=buff) buff.seek(0) return buff - def data_fn(self, obj): + def _data_fn(self, data): pass - def label_fn(self, path): + def _label_fn(self, path: str): pass class _S3PartitionedDataset(_BaseS3Dataset): - - def label_fn(self, path): - return int(re.findall(r'/(.*?)=(.*?)/', path)[-1][1]) + def _label_fn(self, path: str): + return int(re.findall(r"/(.*?)=(.*?)/", path)[-1][1]) class LambdaS3Dataset(_BaseS3Dataset): + """PyTorch S3 Lambda Dataset.""" - def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session: boto3.Session, data_fn: Callable, label_fn: Callable): - """PyTorch S3 Audio Dataset. + def __init__( + self, + path: Union[str, List[str]], + data_fn: Callable, + label_fn: Callable, + suffix: Optional[str] = None, + boto3_session: Optional[boto3.Session] = None, + ): + """PyTorch S3 Lambda Dataset. Parameters ---------- @@ -94,26 +102,33 @@ def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session: boto -------- >>> import awswrangler as wr >>> import boto3 - >>> data_fn = lambda x: torch.tensor(x) - >>> label_fn = lambda x: x.split('.')[-1] - >>> ds = wr.torch.LambdaS3Dataset('s3://bucket/path', boto3.Session(), data_fn=data_fn, label_fn=label_fn) + >>> _data_fn = lambda x: torch.tensor(x) + >>> _label_fn = lambda x: x.split('.')[-1] + >>> ds = wr.torch.LambdaS3Dataset('s3://bucket/path', boto3.Session(), _data_fn=_data_fn, _label_fn=_label_fn) """ super(LambdaS3Dataset, self).__init__(path, suffix, boto3_session) - self._data_fn = data_fn - self._label_fn = label_fn + self._data_func = data_fn + self._label_func = label_fn - def label_fn(self, path): - return self._label_fn(path) + def _label_fn(self, path: str): + return self._label_func(path) - def data_fn(self, data): - print(type(data), data) - return self._data_fn(data) + def _data_fn(self, data): + print(type(data)) + return self._data_func(data) class AudioS3Dataset(_S3PartitionedDataset): + """PyTorch S3 Audio Dataset.""" - def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session: boto3.Session): + def __init__( + self, + path: Union[str, List[str]], + cache_dir: str = "/tmp/", + suffix: Optional[str] = None, + boto3_session: Optional[boto3.Session] = None, + ): """PyTorch S3 Audio Dataset. Assumes audio files are stored with the following structure: @@ -145,17 +160,27 @@ def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session: boto """ super(AudioS3Dataset, self).__init__(path, suffix, boto3_session) + self._cache_dir: str = cache_dir[:-1] if cache_dir.endswith("/") else cache_dir - def data_fn(self, data): - - waveform, sample_rate = torchaudio.load(data) + def _data_fn(self, filename: str) -> Tuple[Any, Any]: # pylint: disable=arguments-differ + waveform, sample_rate = torchaudio.load(filename) + os.remove(path=filename) return waveform, sample_rate + def _fetch_data(self, path: str) -> str: + bucket, key = _utils.parse_path(path=path) + filename: str = f"{self._cache_dir}/{bucket}/{key}" + pathlib.Path(filename).parent.mkdir(parents=True, exist_ok=True) + client_s3 = _utils.client(service_name="s3", session=self._session) + client_s3.download_file(Bucket=bucket, Key=key, Filename=filename) + return filename + class ImageS3Dataset(_S3PartitionedDataset): + """PyTorch S3 Image Dataset.""" def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session: boto3.Session): - """PyTorch Image S3 Dataset. + """PyTorch S3 Image Dataset. Assumes Images are stored with the following structure: @@ -187,7 +212,7 @@ def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session: boto """ super(ImageS3Dataset, self).__init__(path, suffix, boto3_session) - def data_fn(self, data): + def _data_fn(self, data): image = Image.open(data) tensor = to_tensor(image) return tensor diff --git a/pytest.ini b/pytest.ini index d233cbf74..8e7a47ef1 100644 --- a/pytest.ini +++ b/pytest.ini @@ -1,7 +1,7 @@ [pytest] addopts = --verbose - --capture=no + --capture=fd filterwarnings = ignore::DeprecationWarning ignore::UserWarning \ No newline at end of file diff --git a/requirements-dev.txt b/requirements-dev.txt index 137f57383..0491e8789 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -19,4 +19,5 @@ sphinx~=3.0.1 sphinx_bootstrap_theme~=0.7.1 moto~=1.3.14 torch~=1.4.0 -torchvision~=0.5.0 \ No newline at end of file +torchvision~=0.5.0 +torchaudio~=0.4.0 \ No newline at end of file diff --git a/testing/run-validations.sh b/testing/run-validations.sh index 966038ec9..d32fc7808 100755 --- a/testing/run-validations.sh +++ b/testing/run-validations.sh @@ -9,7 +9,7 @@ mv temp.yaml cloudformation.yaml pushd .. black --line-length 120 --target-version py36 awswrangler testing/test_awswrangler isort -rc --line-width 120 awswrangler testing/test_awswrangler -pydocstyle awswrangler/ --add-ignore=D204 +pydocstyle awswrangler/ --add-ignore=D204,D403 mypy awswrangler flake8 setup.py awswrangler testing/test_awswrangler pylint -j 0 awswrangler diff --git a/testing/test_awswrangler/test_torch.py b/testing/test_awswrangler/test_torch.py index a54797440..5b7a84b38 100644 --- a/testing/test_awswrangler/test_torch.py +++ b/testing/test_awswrangler/test_torch.py @@ -1,12 +1,12 @@ import logging - import re + import boto3 import numpy as np import pandas as pd import pytest import torch - +import torchaudio from PIL import Image from torch.utils.data import DataLoader from torchvision.transforms.functional import to_tensor @@ -108,91 +108,89 @@ def test_torch_sql_label(parameters, db_type, chunksize): def test_torch_image_s3(bucket): - wr.s3.delete_objects(path=bucket, boto3_session=boto3.Session()) - + path = f"s3://{bucket}/test_torch_image_s3/" + wr.s3.delete_objects(path=path, boto3_session=boto3.Session()) s3 = boto3.client("s3") ref_label = 0 s3.put_object( - Body=open("../../docs/source/_static/logo.png", "rb").read(), + Body=open("docs/source/_static/logo.png", "rb").read(), Bucket=bucket, - Key=f"class={ref_label}/logo.png", + Key=f"test_torch_image_s3/class={ref_label}/logo.png", ContentType="image/png", ) - ds = wr.torch.ImageS3Dataset(path=bucket, suffix="png", boto3_session=boto3.Session()) + ds = wr.torch.ImageS3Dataset(path=path, suffix="png", boto3_session=boto3.Session()) image, label = ds[0] assert image.shape == torch.Size([4, 494, 1636]) assert label == torch.tensor(ref_label, dtype=torch.int) - - wr.s3.delete_objects(path=bucket, boto3_session=boto3.Session()) + wr.s3.delete_objects(path=path) def test_torch_image_s3_dataloader(bucket): - wr.s3.delete_objects(path=bucket, boto3_session=boto3.Session()) - + path = f"s3://{bucket}/test_torch_image_s3_dataloader/" + wr.s3.delete_objects(path=path) s3 = boto3.client("s3") labels = np.random.randint(0, 4, size=(8,)) for i, label in enumerate(labels): s3.put_object( - Body=open("../../docs/source/_static/logo.png", "rb").read(), + Body=open("./docs/source/_static/logo.png", "rb").read(), Bucket=bucket, - Key=f"class={label}/logo{i}.png", + Key=f"test_torch_image_s3_dataloader/class={label}/logo{i}.png", ContentType="image/png", ) - ds = wr.torch.ImageS3Dataset( - path=bucket, - suffix="png", - boto3_session=boto3.Session(), - ) + ds = wr.torch.ImageS3Dataset(path=path, suffix="png", boto3_session=boto3.Session()) batch_size = 2 num_train = len(ds) indices = list(range(num_train)) loader = DataLoader( - ds, - batch_size=batch_size, - num_workers=4, - sampler=torch.utils.data.sampler.RandomSampler(indices), + ds, batch_size=batch_size, num_workers=4, sampler=torch.utils.data.sampler.RandomSampler(indices) ) for i, (image, label) in enumerate(loader): assert image.shape == torch.Size([batch_size, 4, 494, 1636]) assert label.dtype == torch.int64 - - wr.s3.delete_objects(path=bucket, boto3_session=boto3.Session()) + wr.s3.delete_objects(path=path) def test_torch_lambda_s3(bucket): - wr.s3.delete_objects(path=bucket, boto3_session=boto3.Session()) - + path = f"s3://{bucket}/test_torch_lambda_s3/" + wr.s3.delete_objects(path=path) s3 = boto3.client("s3") ref_label = 0 s3.put_object( - Body=open("../../docs/source/_static/logo.png", "rb").read(), + Body=open("./docs/source/_static/logo.png", "rb").read(), Bucket=bucket, - Key=f"class={ref_label}/logo.png", + Key=f"test_torch_lambda_s3/class={ref_label}/logo.png", ContentType="image/png", ) ds = wr.torch.LambdaS3Dataset( - path=bucket, + path=path, suffix="png", boto3_session=boto3.Session(), data_fn=lambda x: to_tensor(Image.open(x)), - label_fn=lambda x: int(re.findall(r'/class=(.*?)/', x)[-1]), + label_fn=lambda x: int(re.findall(r"/class=(.*?)/", x)[-1]), ) image, label = ds[0] assert image.shape == torch.Size([4, 494, 1636]) assert label == torch.tensor(ref_label, dtype=torch.int) - - wr.s3.delete_objects(path=bucket, boto3_session=boto3.Session()) + wr.s3.delete_objects(path=path) def test_torch_audio_s3(bucket): - ds = wr.torch.AudioS3Dataset( - path="s3://multimedia-commons/data/videos/mp4/006/039/006039642c984a788569c7fea33ef3.mp4", - suffix="png", - boto3_session=boto3.Session(), - ) - loader = DataLoader( - ds, - batch_size=1, + size = (1, 8_000 * 5) + audio = torch.randint(low=-25, high=25, size=size) / 100.0 + audio_file = "/tmp/amazing_sound.wav" + torchaudio.save(audio_file, audio, 8_000) + path = f"s3://{bucket}/test_torch_audio_s3/" + wr.s3.delete_objects(path=path, boto3_session=boto3.Session()) + s3 = boto3.client("s3") + ref_label = 0 + s3.put_object( + Body=open(audio_file, "rb").read(), + Bucket=bucket, + Key=f"test_torch_audio_s3/class={ref_label}/amazing_sound.wav", + ContentType="audio/wav", ) - for image, label in loader: - assert image.shape == torch.Size([1, 28, 28]) + s3_audio_file = f"{bucket}/test_torch_audio_s3/class={ref_label}/amazing_sound.wav" + ds = wr.torch.AudioS3Dataset(path=s3_audio_file, suffix="wav") + loader = DataLoader(ds, batch_size=1) + for (audio, rate), label in loader: + assert audio.shape == torch.Size((1, *size)) From 5a9a83f5dae7b6fe1cba06019c076a516b198756 Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Wed, 22 Apr 2020 20:48:25 -0300 Subject: [PATCH 12/27] s3 iterable dataset --- awswrangler/torch.py | 143 ++++++++++++++++++++++--- testing/test_awswrangler/test_torch.py | 53 ++++++++- 2 files changed, 178 insertions(+), 18 deletions(-) diff --git a/awswrangler/torch.py b/awswrangler/torch.py index db09abc46..c4dac13e5 100644 --- a/awswrangler/torch.py +++ b/awswrangler/torch.py @@ -1,6 +1,8 @@ """PyTorch Module.""" import logging +import io import os +import tarfile import pathlib import re from io import BytesIO @@ -20,8 +22,8 @@ _logger: logging.Logger = logging.getLogger(__name__) -class _BaseS3Dataset(Dataset): - """PyTorch Map-Style S3 Dataset.""" +class _BaseS3Dataset: + """PyTorch Amazon S3 Map-Style Dataset.""" def __init__( self, path: Union[str, List[str]], suffix: Optional[str] = None, boto3_session: Optional[boto3.Session] = None @@ -46,6 +48,52 @@ def __init__( path=path, suffix=suffix, boto3_session=self._session ) + def _fetch_data(self, path: str): + """Add parquet and csv support""" + bucket, key = _utils.parse_path(path=path) + buff = BytesIO() + client_s3: boto3.client = _utils.client(service_name="s3", session=self._session) + client_s3.download_fileobj(Bucket=bucket, Key=key, Fileobj=buff) + buff.seek(0) + return buff + + @staticmethod + def _load_data(data: io.BytesIO, path: str): + if path.endswith('.tar.gz') or path.endswith('.tgz'): + pass + # tarfile.open(fileobj=data) + # tar = tarfile.open(fileobj=data) + # for member in tar.getmembers(): + # print('member', member) + elif path.endswith('.pt'): + data = torch.load(data) + return data + + +class _ListS3Dataset(_BaseS3Dataset, Dataset): + """PyTorch Amazon S3 Map-Style List Dataset.""" + + def __init__( + self, path: Union[str, List[str]], suffix: Optional[str] = None, boto3_session: Optional[boto3.Session] = None + ): + """PyTorch Map-Style List S3 Dataset. + + Each file under path would be handle as a single tensor. + + Parameters + ---------- + path : Union[str, List[str]] + S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + boto3_session : boto3.Session(), optional + Boto3 Session. The default boto3 session will be used if boto3_session receive None. + + Returns + ------- + torch.utils.data.Dataset + + """ + super(_ListS3Dataset, self).__init__(path, suffix, boto3_session) + def __getitem__(self, index): path = self._paths[index] data = self._fetch_data(path) @@ -54,14 +102,6 @@ def __getitem__(self, index): def __len__(self): return len(self._paths) - def _fetch_data(self, path): - bucket, key = _utils.parse_path(path=path) - buff = BytesIO() - client_s3: boto3.client = _utils.client(service_name="s3", session=self._session) - client_s3.download_fileobj(Bucket=bucket, Key=key, Fileobj=buff) - buff.seek(0) - return buff - def _data_fn(self, data): pass @@ -69,13 +109,56 @@ def _label_fn(self, path: str): pass -class _S3PartitionedDataset(_BaseS3Dataset): +class _S3PartitionedDataset(_ListS3Dataset): + """PyTorch Amazon S3 Map-Style Partitioned Dataset.""" + def _label_fn(self, path: str): return int(re.findall(r"/(.*?)=(.*?)/", path)[-1][1]) -class LambdaS3Dataset(_BaseS3Dataset): - """PyTorch S3 Lambda Dataset.""" +class S3FilesDataset(_BaseS3Dataset, Dataset): + """PyTorch Amazon S3 Files Map-Style Dataset.""" + + def __init__( + self, path: Union[str, List[str]], suffix: Optional[str] = None, boto3_session: Optional[boto3.Session] = None + ): + """PyTorch S3 Files Map-Style Dataset. + + Each file under Amazon S3 path would be handled as a batch of tensors. + All files will be loaded to memory since random access is needed. + + Parameters + ---------- + path : Union[str, List[str]] + S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + boto3_session : boto3.Session(), optional + Boto3 Session. The default boto3 session will be used if boto3_session receive None. + + Returns + ------- + torch.utils.data.Dataset + + """ + super(S3FilesDataset, self).__init__(path, suffix, boto3_session) + + def _download_files(self): + self._data = [] + for path in self._paths: + data = self._fetch_data(path) + data = self._load_data(data, path) + self._data.append(data) + + self.data = torch.tensor(self._data) + + def __getitem__(self, index): + return self._data[index] + + def __len__(self): + return len(self._data) + + +class LambdaS3Dataset(_ListS3Dataset): + """PyTorch Amazon S3 Lambda Map-Style Dataset.""" def __init__( self, @@ -218,6 +301,40 @@ def _data_fn(self, data): return tensor +class S3IterableDataset(_BaseS3Dataset, IterableDataset): + """PyTorch Amazon S3 Iterable Dataset.""" + + def __init__( + self, + path: Union[str, List[str]], + suffix: Optional[str] = None, + boto3_session: Optional[boto3.Session] = None, + ): + """PyTorch Amazon S3 Iterable Dataset. + + Parameters + ---------- + path : Union[str, List[str]] + S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + boto3_session : boto3.Session(), optional + Boto3 Session. The default boto3 session will be used if boto3_session receive None. + + Returns + ------- + torch.utils.data.Dataset + + """ + super(S3IterableDataset, self).__init__(path, suffix, boto3_session) + self._paths_index = 0 + + def __iter__(self) -> Union[Iterator[torch.Tensor], Iterator[Tuple[torch.Tensor, torch.Tensor]]]: + for path in self._paths: + data = self._fetch_data(path) + data = self._load_data(data, path) + for d in data: + yield d + + class SQLDataset(IterableDataset): # pylint: disable=too-few-public-methods,abstract-method """Pytorch Iterable SQL Dataset.""" diff --git a/testing/test_awswrangler/test_torch.py b/testing/test_awswrangler/test_torch.py index 5b7a84b38..599976d33 100644 --- a/testing/test_awswrangler/test_torch.py +++ b/testing/test_awswrangler/test_torch.py @@ -1,5 +1,6 @@ -import logging +import io import re +import logging import boto3 import numpy as np @@ -125,13 +126,14 @@ def test_torch_image_s3(bucket): wr.s3.delete_objects(path=path) -def test_torch_image_s3_dataloader(bucket): +@pytest.mark.parametrize("drop_last", [True, False]) +def test_torch_image_s3_dataloader(bucket, drop_last): path = f"s3://{bucket}/test_torch_image_s3_dataloader/" wr.s3.delete_objects(path=path) - s3 = boto3.client("s3") + client_s3 = boto3.client("s3") labels = np.random.randint(0, 4, size=(8,)) for i, label in enumerate(labels): - s3.put_object( + client_s3.put_object( Body=open("./docs/source/_static/logo.png", "rb").read(), Bucket=bucket, Key=f"test_torch_image_s3_dataloader/class={label}/logo{i}.png", @@ -142,7 +144,7 @@ def test_torch_image_s3_dataloader(bucket): num_train = len(ds) indices = list(range(num_train)) loader = DataLoader( - ds, batch_size=batch_size, num_workers=4, sampler=torch.utils.data.sampler.RandomSampler(indices) + ds, batch_size=batch_size, num_workers=4, sampler=torch.utils.data.sampler.RandomSampler(indices), drop_last=drop_last ) for i, (image, label) in enumerate(loader): assert image.shape == torch.Size([batch_size, 4, 494, 1636]) @@ -194,3 +196,44 @@ def test_torch_audio_s3(bucket): loader = DataLoader(ds, batch_size=1) for (audio, rate), label in loader: assert audio.shape == torch.Size((1, *size)) + + +# def test_torch_s3_file_dataset(bucket): +# cifar10 = "s3://fast-ai-imageclas/cifar10.tgz" +# batch_size = 64 +# for image, label in DataLoader( +# wr.torch.S3FilesDataset(cifar10), +# batch_size=batch_size, +# ): +# assert image.shape == torch.Size([batch_size, 3, 32, 32]) +# assert label.dtype == torch.int64 +# break + + +@pytest.mark.parametrize("drop_last", [True, False]) +def test_torch_s3_iterable_dataset(bucket, drop_last): + folder = "test_torch_s3_iterable_dataset" + batch_size = 32 + client_s3 = boto3.client("s3") + for i in range(3): + batch = torch.randn(100, 3, 32, 32) + buff = io.BytesIO() + torch.save(batch, buff) + buff.seek(0) + client_s3.put_object( + Body=buff.read(), + Bucket=bucket, + Key=f"{folder}/file{i}.pt", + ) + + for image in DataLoader( + wr.torch.S3IterableDataset( + path=f"s3://{bucket}/{folder}", + ), + batch_size=batch_size, + drop_last=drop_last, + ): + if drop_last: + assert image.shape == torch.Size([batch_size, 3, 32, 32]) + else: + assert image[0].shape == torch.Size([3, 32, 32]) From 60232f44a5663fce3cdd82b7b5dcaaf431fa2b76 Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Wed, 22 Apr 2020 22:09:58 -0300 Subject: [PATCH 13/27] add tutorial draft --- tutorials/14 - PyTorch.ipynb | 249 +++++++++++++++++++++++++++++++++++ 1 file changed, 249 insertions(+) create mode 100644 tutorials/14 - PyTorch.ipynb diff --git a/tutorials/14 - PyTorch.ipynb b/tutorials/14 - PyTorch.ipynb new file mode 100644 index 000000000..757c817f9 --- /dev/null +++ b/tutorials/14 - PyTorch.ipynb @@ -0,0 +1,249 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "[![AWS Data Wrangler](_static/logo.png \"AWS Data Wrangler\")](https://github.com/awslabs/aws-data-wrangler)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# PyTorch" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Table of Contents\n", + "* [1.Defining Training Function](#1.-Defininf-Training-Function)\n", + "* [2.Traning From Amazon S3](#1.-Traning-From-Amazon-S3)\n", + "\t* [2.1 Writing PyTorch Dataset to S3](#1.1-Writing-PyTorch-Dataset-to-S3)\n", + "\t* [2.2 Training Network](#1.2-Training-Network)\n", + "* [3. Training From SQL Query](#2.-Training-From-SQL-Query)\n", + "\t* [3.1 Writing Data to SQL Database](#2.1-Writing-Data-to-SQL-Database)\n", + "\t* [3.3 Training Network From SQL](#2.2-Reading-single-JSON-file)\n", + "* [4. Creating Custom S3 Dataset](#1.-Creating-Custom-S3-Dataset)\n", + "\t* [4.1 Creating Custom PyTorch Dataset](#1.1-Creating-Custom-PyTorch-Dataset)\n", + "\t* [4.2 Writing Data to S3](#1.1-Writing-Data-to-S3)\n", + "\t* [4.3 Training Network](#1.2-Training-Network)\n", + "* [5. Delete objects](#6.-Delete-objects)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import io\n", + "import boto3\n", + "import torch\n", + "import torchvision\n", + "import awswrangler as wr\n", + "\n", + "accuracy = lambda o, l: 100/o.size(0) * (torch.max(o.data, 1)[1] == l).sum().item()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import getpass\n", + "bucket = getpass.getpass()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 1. Defining Training Function" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def train(model, dataset):\n", + " criterion = torch.nn.CrossEntropyLoss()\n", + " opt = torch.optim.SGD(model.parameters(), 0.025)\n", + "\n", + " for epoch in range(2):\n", + "\n", + " model.train()\n", + " for inputs, labels in torch.utils.data.DataLoader(\n", + " dataset,\n", + " batch_size=64,\n", + " num_workers=2,\n", + " ):\n", + "\n", + " outputs = model(inputs)\n", + " loss = criterion(outputs, labels)\n", + " loss.backward()\n", + " opt.step()s\n", + " opt.zero_grad()\n", + "\n", + " acc = accuracy(outputs, labels)\n", + " print(f'batch: {i} loss: {loss.mean().item():.4f} batch_acc: {acc:.2f}') " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 2. Traning From Amazon S3" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "client_s3 = boto3.client(\"s3\")\n", + "folder = \"tutorial_torch_dataset\"\n", + "for i in range(3):\n", + " batch = (\n", + " torch.randn(100, 3, 32, 32),\n", + " torch.randint(1, size=(100,)),\n", + " )\n", + " buff = io.BytesIO()\n", + " torch.save(batch, buff)\n", + " buff.seek(0)\n", + " client_s3.put_object(\n", + " Body=buff.read(),\n", + " Bucket=bucket,\n", + " Key=f\"{folder}/file{i}.pt\",\n", + " )" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2.2 Training Network" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "train(\n", + " torchvision.models.resnet18(),\n", + " wr.torch.S3IterableDataset(path=f\"s3://{bucket}/{folder}\"),\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 2. Training Directly From SQL Query" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2.1 Writing Data to SQL Database" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "eng = wr.catalog.get_engine(\"aws-data-wrangler-redshift\")\n", + "df = pd.DataFrame({\n", + " \"height\": [2, 1.4, 1.7, 1.8, 1.9],\n", + " \"name\": [\"foo\", \"boo\"],\n", + " \"target\": [1, 0, 0, 1, 2, 3]\n", + "})\n", + "\n", + "wr.db.to_sql(\n", + " df,\n", + " eng_redshift,\n", + " schema=\"public\",\n", + " name=\"torch\",\n", + " if_exists=\"replace\",\n", + " index=False\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2.2 Training Network From SQL" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "train(\n", + " model = torch.nn.Sequential(\n", + " torch.nn.Linear(, 20),\n", + " torch.nn.ReLU(),\n", + " torch.nn.Linear(20, 2), \n", + " ),\n", + " wr.torch.SQLDataset(\n", + " sql=\"SELECT * FROM public.torch\"\n", + " con=eng\n", + " label_col=\"target\",\n", + " chunksize=100\n", + " )\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 3. Delete Objects" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "wr.s3.delete_objects(f\"s3://{bucket}/\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "conda_pytorch_p36", + "language": "python", + "name": "conda_pytorch_p36" + }, + "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.6.5" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} From 215fbd54c75f852267ced4777f9956391f4bb989 Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Thu, 23 Apr 2020 11:51:00 -0300 Subject: [PATCH 14/27] add torch extras_requirements to setuptools --- requirements-torch.txt | 3 +++ setup.py | 3 +++ 2 files changed, 6 insertions(+) create mode 100644 requirements-torch.txt diff --git a/requirements-torch.txt b/requirements-torch.txt new file mode 100644 index 000000000..325196f07 --- /dev/null +++ b/requirements-torch.txt @@ -0,0 +1,3 @@ +torch~=1.4.0 +torchvision~=0.5.0 +torchaudio~=0.4.0 \ No newline at end of file diff --git a/setup.py b/setup.py index b363e6e58..f9c861a60 100644 --- a/setup.py +++ b/setup.py @@ -23,4 +23,7 @@ packages=find_packages(include=["awswrangler", "awswrangler.*"], exclude=["tests"]), python_requires=">=3.6, <3.9", install_requires=[open("requirements.txt").read().strip().split("\n")], + extras_require={ + "torch": open("requirements-torch.txt").read().strip().split("\n") + } ) From 0ad9e4bf16e015562aeaed0a635ca970335b420f Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Thu, 23 Apr 2020 12:46:30 -0300 Subject: [PATCH 15/27] handle labels in S3IterableDataset --- awswrangler/torch.py | 11 ++++++++ testing/test_awswrangler/test_torch.py | 37 ++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/awswrangler/torch.py b/awswrangler/torch.py index c4dac13e5..29343983b 100644 --- a/awswrangler/torch.py +++ b/awswrangler/torch.py @@ -5,6 +5,7 @@ import tarfile import pathlib import re +from collections import Iterable from io import BytesIO from typing import Any, Callable, Iterator, List, Optional, Tuple, Union @@ -331,10 +332,20 @@ def __iter__(self) -> Union[Iterator[torch.Tensor], Iterator[Tuple[torch.Tensor, for path in self._paths: data = self._fetch_data(path) data = self._load_data(data, path) + + if isinstance(data, torch.Tensor): + pass + elif isinstance(data, Iterable) and all([isinstance(d, torch.Tensor) for d in data]): + data = zip(data) + else: + raise NotImplementedError(f"ERROR: Type: {type(data)} has not been implemented!") + for d in data: yield d + + class SQLDataset(IterableDataset): # pylint: disable=too-few-public-methods,abstract-method """Pytorch Iterable SQL Dataset.""" diff --git a/testing/test_awswrangler/test_torch.py b/testing/test_awswrangler/test_torch.py index 599976d33..aaac654a4 100644 --- a/testing/test_awswrangler/test_torch.py +++ b/testing/test_awswrangler/test_torch.py @@ -237,3 +237,40 @@ def test_torch_s3_iterable_dataset(bucket, drop_last): assert image.shape == torch.Size([batch_size, 3, 32, 32]) else: assert image[0].shape == torch.Size([3, 32, 32]) + + +@pytest.mark.parametrize("drop_last", [True, False]) +def test_torch_s3_iterable_with_labels(bucket, drop_last): + folder = "test_torch_s3_iterable_dataset" + batch_size = 32 + client_s3 = boto3.client("s3") + for i in range(3): + batch = ( + torch.randn(100, 3, 32, 32), + torch.randint(2, size=(100,)), + ) + buff = io.BytesIO() + torch.save(batch, buff) + buff.seek(0) + client_s3.put_object( + Body=buff.read(), + Bucket=bucket, + Key=f"{folder}/file{i}.pt", + ) + + for images, labels in DataLoader( + wr.torch.S3IterableDataset( + path=f"s3://{bucket}/{folder}", + ), + batch_size=batch_size, + drop_last=drop_last, + ): + if drop_last: + assert images.shape == torch.Size([batch_size, 3, 32, 32]) + assert labels.dtype == torch.int64 + assert labels.size == torch.Size([batch_size, 1]) + + else: + assert images[0].shape == torch.Size([3, 32, 32]) + assert labels.dtype == torch.int64 + assert labels.size == torch.Size([1]) \ No newline at end of file From 5e72ddf1232c8cde025080a32ebf4cac398f833c Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Thu, 23 Apr 2020 12:59:01 -0300 Subject: [PATCH 16/27] clear bucket in S3Iterable Dataset test --- awswrangler/torch.py | 2 +- testing/test_awswrangler/test_torch.py | 16 ++++++++++------ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/awswrangler/torch.py b/awswrangler/torch.py index 29343983b..5e4365062 100644 --- a/awswrangler/torch.py +++ b/awswrangler/torch.py @@ -336,7 +336,7 @@ def __iter__(self) -> Union[Iterator[torch.Tensor], Iterator[Tuple[torch.Tensor, if isinstance(data, torch.Tensor): pass elif isinstance(data, Iterable) and all([isinstance(d, torch.Tensor) for d in data]): - data = zip(data) + data = zip(*data) else: raise NotImplementedError(f"ERROR: Type: {type(data)} has not been implemented!") diff --git a/testing/test_awswrangler/test_torch.py b/testing/test_awswrangler/test_torch.py index aaac654a4..83630b0e7 100644 --- a/testing/test_awswrangler/test_torch.py +++ b/testing/test_awswrangler/test_torch.py @@ -211,8 +211,10 @@ def test_torch_audio_s3(bucket): @pytest.mark.parametrize("drop_last", [True, False]) -def test_torch_s3_iterable_dataset(bucket, drop_last): - folder = "test_torch_s3_iterable_dataset" +def test_torch_s3_iterable(bucket, drop_last): + folder = "test_torch_s3_iterable" + path = f"s3://{bucket}/{folder}/" + wr.s3.delete_objects(path=path) batch_size = 32 client_s3 = boto3.client("s3") for i in range(3): @@ -241,7 +243,9 @@ def test_torch_s3_iterable_dataset(bucket, drop_last): @pytest.mark.parametrize("drop_last", [True, False]) def test_torch_s3_iterable_with_labels(bucket, drop_last): - folder = "test_torch_s3_iterable_dataset" + folder = "test_torch_s3_iterable_with_labels" + path = f"s3://{bucket}/{folder}/" + wr.s3.delete_objects(path=path) batch_size = 32 client_s3 = boto3.client("s3") for i in range(3): @@ -268,9 +272,9 @@ def test_torch_s3_iterable_with_labels(bucket, drop_last): if drop_last: assert images.shape == torch.Size([batch_size, 3, 32, 32]) assert labels.dtype == torch.int64 - assert labels.size == torch.Size([batch_size, 1]) + assert labels.shape == torch.Size([batch_size]) else: assert images[0].shape == torch.Size([3, 32, 32]) - assert labels.dtype == torch.int64 - assert labels.size == torch.Size([1]) \ No newline at end of file + assert labels[0].dtype == torch.int64 + assert labels[0].shape == torch.Size([]) From 5b399ac656be04e1c4cb5cf454cad5ea474a4b10 Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Thu, 23 Apr 2020 13:10:07 -0300 Subject: [PATCH 17/27] update setuptools --- requirements-dev.txt | 5 +---- setup-dev-env.sh | 3 +-- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 0491e8789..3fdd3cdf3 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -17,7 +17,4 @@ twine~=3.1.1 wheel~=0.34.2 sphinx~=3.0.1 sphinx_bootstrap_theme~=0.7.1 -moto~=1.3.14 -torch~=1.4.0 -torchvision~=0.5.0 -torchaudio~=0.4.0 \ No newline at end of file +moto~=1.3.14 \ No newline at end of file diff --git a/setup-dev-env.sh b/setup-dev-env.sh index 692724ee0..c9c2e9902 100755 --- a/setup-dev-env.sh +++ b/setup-dev-env.sh @@ -3,5 +3,4 @@ set -ex pip install --upgrade pip pip install -r requirements-dev.txt -pip install -r requirements.txt -pip install -e . +pip install -e ".[torch]" From 2db15b6d09ae1d5e80d325a7daf44ab8c163eeef Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Thu, 23 Apr 2020 13:23:08 -0300 Subject: [PATCH 18/27] update pytorch tutorial --- tutorials/14 - PyTorch.ipynb | 69 +++++++++++++++++++++++++----------- 1 file changed, 48 insertions(+), 21 deletions(-) diff --git a/tutorials/14 - PyTorch.ipynb b/tutorials/14 - PyTorch.ipynb index 757c817f9..fefb8332a 100644 --- a/tutorials/14 - PyTorch.ipynb +++ b/tutorials/14 - PyTorch.ipynb @@ -35,7 +35,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 1, "metadata": {}, "outputs": [], "source": [ @@ -45,12 +45,14 @@ "import torchvision\n", "import awswrangler as wr\n", "\n", - "accuracy = lambda o, l: 100/o.size(0) * (torch.max(o.data, 1)[1] == l).sum().item()" + "from torch.optim import SGD\n", + "from torch.nn import CrossEntropyLoss\n", + "from torch.utils.data import DataLoader" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 2, "metadata": {}, "outputs": [], "source": [ @@ -67,31 +69,37 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 4, "metadata": {}, "outputs": [], "source": [ - "def train(model, dataset):\n", - " criterion = torch.nn.CrossEntropyLoss()\n", - " opt = torch.optim.SGD(model.parameters(), 0.025)\n", + "def train(model, dataset, batch_size=64, epochs=2, device='cpu'):\n", + "\n", + " criterion = CrossEntropyLoss().to(device)\n", + " opt = SGD(model.parameters(), 0.025)\n", + " loader = DataLoader(dataset, batch_size=batch_size, num_workers=1)\n", "\n", - " for epoch in range(2):\n", + " for epoch in range(epochs):\n", "\n", + " correct = 0 \n", " model.train()\n", - " for inputs, labels in torch.utils.data.DataLoader(\n", - " dataset,\n", - " batch_size=64,\n", - " num_workers=2,\n", - " ):\n", + " for i, (inputs, labels) in enumerate(loader):\n", "\n", + " # Forward Pass\n", " outputs = model(inputs)\n", + " \n", + " # Backward Pass\n", " loss = criterion(outputs, labels)\n", " loss.backward()\n", - " opt.step()s\n", + " opt.step()\n", " opt.zero_grad()\n", + " \n", + " # Accuracy\n", + " _, predicted = torch.max(outputs.data, 1)\n", + " correct += (predicted == labels).sum().item()\n", + " accuracy = 100 * correct / ((i+1) * batch_size)\n", "\n", - " acc = accuracy(outputs, labels)\n", - " print(f'batch: {i} loss: {loss.mean().item():.4f} batch_acc: {acc:.2f}') " + " print(f'batch: {i} loss: {loss.mean().item():.4f} acc: {accuracy:.2f}') " ] }, { @@ -103,16 +111,18 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "client_s3 = boto3.client(\"s3\")\n", "folder = \"tutorial_torch_dataset\"\n", + "\n", + "wr.s3.delete_objects(f\"s3://{bucket}/{folder}\")\n", "for i in range(3):\n", " batch = (\n", " torch.randn(100, 3, 32, 32),\n", - " torch.randint(1, size=(100,)),\n", + " torch.randint(2, size=(100,)),\n", " )\n", " buff = io.BytesIO()\n", " torch.save(batch, buff)\n", @@ -133,13 +143,30 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 6, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "batch: 0 loss: 6.9552 acc: 0.00\n", + "batch: 1 loss: 2.9621 acc: 23.44\n", + "batch: 2 loss: 0.9873 acc: 31.77\n", + "batch: 3 loss: 1.9760 acc: 34.38\n", + "batch: 4 loss: 3.3523 acc: 33.44\n", + "batch: 0 loss: 1.2023 acc: 59.38\n", + "batch: 1 loss: 0.8057 acc: 60.16\n", + "batch: 2 loss: 0.6782 acc: 62.50\n", + "batch: 3 loss: 0.4291 acc: 67.58\n", + "batch: 4 loss: 0.2953 acc: 66.88\n" + ] + } + ], "source": [ "train(\n", " torchvision.models.resnet18(),\n", - " wr.torch.S3IterableDataset(path=f\"s3://{bucket}/{folder}\"),\n", + " wr.torch.S3IterableDataset(path=f\"{bucket}/{folder}\")\n", ")" ] }, From 5e647c66d0f4df62ed360d73d0a3a3aa0bbda06c Mon Sep 17 00:00:00 2001 From: igorborgest Date: Thu, 23 Apr 2020 17:01:50 +0000 Subject: [PATCH 19/27] Update tutorial --- tutorials/14 - PyTorch.ipynb | 101 +++++++++++++++++++++++------------ 1 file changed, 68 insertions(+), 33 deletions(-) diff --git a/tutorials/14 - PyTorch.ipynb b/tutorials/14 - PyTorch.ipynb index fefb8332a..a3d988881 100644 --- a/tutorials/14 - PyTorch.ipynb +++ b/tutorials/14 - PyTorch.ipynb @@ -40,9 +40,11 @@ "outputs": [], "source": [ "import io\n", + "\n", "import boto3\n", "import torch\n", "import torchvision\n", + "import pandas as pd\n", "import awswrangler as wr\n", "\n", "from torch.optim import SGD\n", @@ -54,7 +56,15 @@ "cell_type": "code", "execution_count": 2, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + " ··········································\n" + ] + } + ], "source": [ "import getpass\n", "bucket = getpass.getpass()" @@ -69,15 +79,15 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 3, "metadata": {}, "outputs": [], "source": [ - "def train(model, dataset, batch_size=64, epochs=2, device='cpu'):\n", + "def train(model, dataset, batch_size=64, epochs=2, device='cpu', num_workers=1):\n", "\n", " criterion = CrossEntropyLoss().to(device)\n", " opt = SGD(model.parameters(), 0.025)\n", - " loader = DataLoader(dataset, batch_size=batch_size, num_workers=1)\n", + " loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers)\n", "\n", " for epoch in range(epochs):\n", "\n", @@ -111,7 +121,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 4, "metadata": {}, "outputs": [], "source": [ @@ -143,23 +153,23 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "batch: 0 loss: 6.9552 acc: 0.00\n", - "batch: 1 loss: 2.9621 acc: 23.44\n", - "batch: 2 loss: 0.9873 acc: 31.77\n", - "batch: 3 loss: 1.9760 acc: 34.38\n", - "batch: 4 loss: 3.3523 acc: 33.44\n", - "batch: 0 loss: 1.2023 acc: 59.38\n", - "batch: 1 loss: 0.8057 acc: 60.16\n", - "batch: 2 loss: 0.6782 acc: 62.50\n", - "batch: 3 loss: 0.4291 acc: 67.58\n", - "batch: 4 loss: 0.2953 acc: 66.88\n" + "batch: 0 loss: 7.0221 acc: 0.00\n", + "batch: 1 loss: 2.7788 acc: 23.44\n", + "batch: 2 loss: 0.9828 acc: 32.29\n", + "batch: 3 loss: 0.9414 acc: 39.45\n", + "batch: 4 loss: 1.0737 acc: 39.38\n", + "batch: 0 loss: 1.2178 acc: 50.00\n", + "batch: 1 loss: 1.4069 acc: 51.56\n", + "batch: 2 loss: 1.0783 acc: 52.08\n", + "batch: 3 loss: 0.9926 acc: 52.34\n", + "batch: 4 loss: 1.1111 acc: 49.06\n" ] } ], @@ -186,20 +196,20 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "eng = wr.catalog.get_engine(\"aws-data-wrangler-redshift\")\n", "df = pd.DataFrame({\n", - " \"height\": [2, 1.4, 1.7, 1.8, 1.9],\n", - " \"name\": [\"foo\", \"boo\"],\n", - " \"target\": [1, 0, 0, 1, 2, 3]\n", + " \"height\": [2, 1.4, 1.7, 1.8, 1.9, 2.2],\n", + " \"weigth\": [100.0, 50.0, 70.0, 80.0, 90.0, 160.0],\n", + " \"target\": [1, 0, 0, 1, 1, 1]\n", "})\n", "\n", "wr.db.to_sql(\n", " df,\n", - " eng_redshift,\n", + " eng,\n", " schema=\"public\",\n", " name=\"torch\",\n", " if_exists=\"replace\",\n", @@ -216,22 +226,47 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 7, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "batch: 0 loss: 5.0253 acc: 50.00\n", + "batch: 1 loss: 21.3174 acc: 50.00\n", + "batch: 2 loss: 0.5061 acc: 66.67\n", + "batch: 0 loss: 1.2222 acc: 50.00\n", + "batch: 1 loss: 0.7075 acc: 50.00\n", + "batch: 2 loss: 0.7077 acc: 50.00\n", + "batch: 0 loss: 0.9302 acc: 50.00\n", + "batch: 1 loss: 0.6960 acc: 50.00\n", + "batch: 2 loss: 0.6018 acc: 66.67\n", + "batch: 0 loss: 1.1284 acc: 50.00\n", + "batch: 1 loss: 0.7077 acc: 50.00\n", + "batch: 2 loss: 0.6791 acc: 50.00\n", + "batch: 0 loss: 1.0030 acc: 50.00\n", + "batch: 1 loss: 0.7053 acc: 50.00\n", + "batch: 2 loss: 0.6318 acc: 50.00\n" + ] + } + ], "source": [ "train(\n", - " model = torch.nn.Sequential(\n", - " torch.nn.Linear(, 20),\n", + " torch.nn.Sequential(\n", + " torch.nn.Linear(2, 10),\n", " torch.nn.ReLU(),\n", - " torch.nn.Linear(20, 2), \n", + " torch.nn.Linear(10, 2), \n", " ),\n", " wr.torch.SQLDataset(\n", - " sql=\"SELECT * FROM public.torch\"\n", - " con=eng\n", + " sql=\"SELECT * FROM public.torch\",\n", + " con=eng,\n", " label_col=\"target\",\n", - " chunksize=100\n", - " )\n", + " chunksize=2\n", + " ),\n", + " num_workers=0,\n", + " batch_size=2,\n", + " epochs=5\n", ")" ] }, @@ -244,7 +279,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 8, "metadata": {}, "outputs": [], "source": [ @@ -254,9 +289,9 @@ ], "metadata": { "kernelspec": { - "display_name": "conda_pytorch_p36", + "display_name": "conda_python3", "language": "python", - "name": "conda_pytorch_p36" + "name": "conda_python3" }, "language_info": { "codemirror_mode": { From b3d9fe2d9d4c1563aecb225f6a2b678414df41ab Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Thu, 23 Apr 2020 18:14:55 -0300 Subject: [PATCH 20/27] parallel tests fix --- awswrangler/torch.py | 209 ++++++++++++++++--------- building/build-docs.sh | 2 +- docs/source/api.rst | 13 ++ testing/test_awswrangler/test_torch.py | 37 +++-- 4 files changed, 169 insertions(+), 92 deletions(-) diff --git a/awswrangler/torch.py b/awswrangler/torch.py index 5e4365062..c25e145ee 100644 --- a/awswrangler/torch.py +++ b/awswrangler/torch.py @@ -113,49 +113,54 @@ def _label_fn(self, path: str): class _S3PartitionedDataset(_ListS3Dataset): """PyTorch Amazon S3 Map-Style Partitioned Dataset.""" - def _label_fn(self, path: str): - return int(re.findall(r"/(.*?)=(.*?)/", path)[-1][1]) - - -class S3FilesDataset(_BaseS3Dataset, Dataset): - """PyTorch Amazon S3 Files Map-Style Dataset.""" - - def __init__( - self, path: Union[str, List[str]], suffix: Optional[str] = None, boto3_session: Optional[boto3.Session] = None - ): - """PyTorch S3 Files Map-Style Dataset. - - Each file under Amazon S3 path would be handled as a batch of tensors. - All files will be loaded to memory since random access is needed. - - Parameters - ---------- - path : Union[str, List[str]] - S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). - boto3_session : boto3.Session(), optional - Boto3 Session. The default boto3 session will be used if boto3_session receive None. - - Returns - ------- - torch.utils.data.Dataset - - """ - super(S3FilesDataset, self).__init__(path, suffix, boto3_session) - - def _download_files(self): - self._data = [] - for path in self._paths: - data = self._fetch_data(path) - data = self._load_data(data, path) - self._data.append(data) - - self.data = torch.tensor(self._data) - - def __getitem__(self, index): - return self._data[index] - - def __len__(self): - return len(self._data) + def _label_fn(self, path: str) -> torch.Tensor: + label = int(re.findall(r"/(.*?)=(.*?)/", path)[-1][1]) + return torch.tensor([label]) + + +# class S3FilesDataset(_BaseS3Dataset, Dataset): +# """PyTorch Amazon S3 Files Map-Style Dataset.""" +# +# def __init__( +# self, path: Union[str, List[str]], suffix: Optional[str] = None, boto3_session: Optional[boto3.Session] = None +# ): +# """PyTorch S3 Files Map-Style Dataset. +# +# Each file under Amazon S3 path would be handled as a tensor or batch of tensors. +# +# Note +# ---- +# All files will be loaded to memory since random access is needed. +# +# Parameters +# ---------- +# path : Union[str, List[str]] +# S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). +# boto3_session : boto3.Session(), optional +# Boto3 Session. The default boto3 session will be used if boto3_session receive None. +# +# Returns +# ------- +# torch.utils.data.Dataset +# +# """ +# super(S3FilesDataset, self).__init__(path, suffix, boto3_session) +# self._download_files() +# +# def _download_files(self) -> None: +# self._data = [] +# for path in self._paths: +# data = self._fetch_data(path) +# data = self._load_data(data, path) +# self._data.append(data) +# +# self.data = torch.cat(self._data, dim=0) +# +# def __getitem__(self, index): +# return self._data[index] +# +# def __len__(self): +# return len(self._data) class LambdaS3Dataset(_ListS3Dataset): @@ -169,7 +174,7 @@ def __init__( suffix: Optional[str] = None, boto3_session: Optional[boto3.Session] = None, ): - """PyTorch S3 Lambda Dataset. + """PyTorch Amazon S3 Lambda Dataset. Parameters ---------- @@ -184,22 +189,24 @@ def __init__( Examples -------- + >>> import re + >>> import torch >>> import awswrangler as wr - >>> import boto3 - >>> _data_fn = lambda x: torch.tensor(x) - >>> _label_fn = lambda x: x.split('.')[-1] - >>> ds = wr.torch.LambdaS3Dataset('s3://bucket/path', boto3.Session(), _data_fn=_data_fn, _label_fn=_label_fn) + >>> ds = wr.torch.LambdaS3Dataset( + >>> 's3://bucket/path', + >>> data_fn=lambda x: torch.load(x), + >>> label_fn=lambda x: torch.Tensor(int(re.findall(r"/class=(.*?)/", x)[-1])), + >>> ) """ super(LambdaS3Dataset, self).__init__(path, suffix, boto3_session) self._data_func = data_fn self._label_func = label_fn - def _label_fn(self, path: str): + def _label_fn(self, path: str) -> torch.Tensor: return self._label_func(path) - def _data_fn(self, data): - print(type(data)) + def _data_fn(self, data) -> torch.Tensor: return self._data_func(data) @@ -213,17 +220,26 @@ def __init__( suffix: Optional[str] = None, boto3_session: Optional[boto3.Session] = None, ): - """PyTorch S3 Audio Dataset. + """PyTorch Amazon S3 Audio Dataset. + + Read individual WAV audio files stores in Amazon S3 and return + them as torch tensors. + + Note + ---- + + This dataset assumes audio files are stored with the following structure: + - Assumes audio files are stored with the following structure: + :: - bucket - ├── class=0 - │ ├── audio0.wav - │ └── audio1.wav - └── class=1 - ├── audio2.wav - └── audio3.wav + bucket + ├── class=0 + │ ├── audio0.wav + │ └── audio1.wav + └── class=1 + ├── audio2.wav + └── audio3.wav Parameters ---------- @@ -238,9 +254,39 @@ def __init__( Examples -------- + + Create a Audio S3 Dataset + >>> import awswrangler as wr - >>> import boto3 - >>> ds = wr.torch.AudioS3Dataset('s3://bucket/path', boto3.Session()) + >>> ds = wr.torch.AudioS3Dataset('s3://bucket/path') + + + Training a Model + + >>> criterion = CrossEntropyLoss().to(device) + >>> opt = SGD(model.parameters(), 0.025) + >>> loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers) + >>> + >>> for epoch in range(epochs): + >>> + >>> correct = 0 + >>> model.train() + >>> for i, (inputs, labels) in enumerate(loader): + >>> + >>> # Forward Pass + >>> outputs = model(inputs) + >>> + >>> # Backward Pass + >>> loss = criterion(outputs, labels) + >>> loss.backward() + >>> opt.step() + >>> opt.zero_grad() + >>> + >>> # Accuracy + >>> _, predicted = torch.max(outputs.data, 1) + >>> correct += (predicted == labels).sum().item() + >>> accuracy = 100 * correct / ((i+1) * batch_size) + >>> print(f'batch: {i} loss: {loss.mean().item():.4f} acc: {accuracy:.2f}') """ super(AudioS3Dataset, self).__init__(path, suffix, boto3_session) @@ -261,20 +307,28 @@ def _fetch_data(self, path: str) -> str: class ImageS3Dataset(_S3PartitionedDataset): - """PyTorch S3 Image Dataset.""" + """PyTorch Amazon S3 Image Dataset.""" def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session: boto3.Session): - """PyTorch S3 Image Dataset. + """PyTorch Amazon S3 Image Dataset. + + ImageS3Dataset assumes images are patitioned (within class= folders) in Amazon S3. + Each lisited object will be loaded by default Pillow library. + Note + ---- Assumes Images are stored with the following structure: - bucket - ├── class=0 - │ ├── img0.jpeg - │ └── img1.jpeg - └── class=1 - ├── img2.jpeg - └── img3.jpeg + + :: + + bucket + ├── class=0 + │ ├── img0.jpeg + │ └── img1.jpeg + └── class=1 + ├── img2.jpeg + └── img3.jpeg Parameters ---------- @@ -290,13 +344,12 @@ def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session: boto Examples -------- >>> import awswrangler as wr - >>> import boto3 - >>> ds = wr.torch.ImageS3Dataset('s3://bucket/path', boto3.Session()) + >>> ds = wr.torch.ImageS3Dataset('s3://bucket/path') """ super(ImageS3Dataset, self).__init__(path, suffix, boto3_session) - def _data_fn(self, data): + def _data_fn(self, data: io.BytesIO) -> torch.Tensor: image = Image.open(data) tensor = to_tensor(image) return tensor @@ -324,9 +377,13 @@ def __init__( ------- torch.utils.data.Dataset + Examples + -------- + >>> import awswrangler as wr + >>> ds = wr.torch.S3IterableDataset('s3://bucket/path') + """ super(S3IterableDataset, self).__init__(path, suffix, boto3_session) - self._paths_index = 0 def __iter__(self) -> Union[Iterator[torch.Tensor], Iterator[Tuple[torch.Tensor, torch.Tensor]]]: for path in self._paths: @@ -344,8 +401,6 @@ def __iter__(self) -> Union[Iterator[torch.Tensor], Iterator[Tuple[torch.Tensor, yield d - - class SQLDataset(IterableDataset): # pylint: disable=too-few-public-methods,abstract-method """Pytorch Iterable SQL Dataset.""" diff --git a/building/build-docs.sh b/building/build-docs.sh index c32c20aa0..8c807b485 100755 --- a/building/build-docs.sh +++ b/building/build-docs.sh @@ -4,4 +4,4 @@ set -ex pushd .. rm -rf docs/build docs/source/stubs make -C docs/ html -doc8 --ignore D005 docs/source +doc8 --ignore D005,D002 docs/source diff --git a/docs/source/api.rst b/docs/source/api.rst index 897fc7a3e..aea8bbed6 100644 --- a/docs/source/api.rst +++ b/docs/source/api.rst @@ -3,6 +3,19 @@ API Reference ============= +PyTorch +------- + +.. currentmodule:: awswrangler.torch + +.. autosummary:: + :toctree: stubs + + AudioS3Dataset + ImageS3Dataset + S3IterableDataset + SQLDataset + Amazon S3 --------- diff --git a/testing/test_awswrangler/test_torch.py b/testing/test_awswrangler/test_torch.py index 83630b0e7..40ecf7050 100644 --- a/testing/test_awswrangler/test_torch.py +++ b/testing/test_awswrangler/test_torch.py @@ -63,7 +63,7 @@ def parameters(cloudformation_outputs): @pytest.mark.parametrize("db_type", ["mysql", "redshift", "postgresql"]) def test_torch_sql(parameters, db_type, chunksize): schema = parameters[db_type]["schema"] - table = "test_torch_sql" + table = f"test_torch_sql_{db_type}_{str(chunksize).lower()}" engine = wr.catalog.get_engine(connection=f"aws-data-wrangler-{db_type}") wr.db.to_sql( df=pd.DataFrame({"a": [1.0, 2.0, 3.0], "b": [4.0, 5.0, 6.0]}), @@ -86,7 +86,7 @@ def test_torch_sql(parameters, db_type, chunksize): @pytest.mark.parametrize("db_type", ["mysql", "redshift", "postgresql"]) def test_torch_sql_label(parameters, db_type, chunksize): schema = parameters[db_type]["schema"] - table = "test_torch_sql_label" + table = f"test_torch_sql_label_{db_type}_{str(chunksize).lower()}" engine = wr.catalog.get_engine(connection=f"aws-data-wrangler-{db_type}") wr.db.to_sql( df=pd.DataFrame({"a": [1.0, 2.0, 3.0], "b": [4.0, 5.0, 6.0], "c": [7, 8, 9]}), @@ -109,14 +109,15 @@ def test_torch_sql_label(parameters, db_type, chunksize): def test_torch_image_s3(bucket): - path = f"s3://{bucket}/test_torch_image_s3/" + folder = "test_torch_image_s3" + path = f"s3://{bucket}/{folder}/" wr.s3.delete_objects(path=path, boto3_session=boto3.Session()) s3 = boto3.client("s3") ref_label = 0 s3.put_object( Body=open("docs/source/_static/logo.png", "rb").read(), Bucket=bucket, - Key=f"test_torch_image_s3/class={ref_label}/logo.png", + Key=f"{folder}/class={ref_label}/logo.png", ContentType="image/png", ) ds = wr.torch.ImageS3Dataset(path=path, suffix="png", boto3_session=boto3.Session()) @@ -127,8 +128,9 @@ def test_torch_image_s3(bucket): @pytest.mark.parametrize("drop_last", [True, False]) -def test_torch_image_s3_dataloader(bucket, drop_last): - path = f"s3://{bucket}/test_torch_image_s3_dataloader/" +def test_torch_image_s3(bucket, drop_last): + folder = f"test_torch_image_s3_{str(drop_last).lower()}" + path = f"s3://{bucket}/{folder}/" wr.s3.delete_objects(path=path) client_s3 = boto3.client("s3") labels = np.random.randint(0, 4, size=(8,)) @@ -136,7 +138,7 @@ def test_torch_image_s3_dataloader(bucket, drop_last): client_s3.put_object( Body=open("./docs/source/_static/logo.png", "rb").read(), Bucket=bucket, - Key=f"test_torch_image_s3_dataloader/class={label}/logo{i}.png", + Key=f"{folder}/class={label}/logo{i}.png", ContentType="image/png", ) ds = wr.torch.ImageS3Dataset(path=path, suffix="png", boto3_session=boto3.Session()) @@ -181,14 +183,15 @@ def test_torch_audio_s3(bucket): audio = torch.randint(low=-25, high=25, size=size) / 100.0 audio_file = "/tmp/amazing_sound.wav" torchaudio.save(audio_file, audio, 8_000) - path = f"s3://{bucket}/test_torch_audio_s3/" - wr.s3.delete_objects(path=path, boto3_session=boto3.Session()) + folder = "test_torch_audio_s3" + path = f"s3://{bucket}/{folder}/" + wr.s3.delete_objects(path=path) s3 = boto3.client("s3") ref_label = 0 s3.put_object( Body=open(audio_file, "rb").read(), Bucket=bucket, - Key=f"test_torch_audio_s3/class={ref_label}/amazing_sound.wav", + Key=f"{folder}/class={ref_label}/amazing_sound.wav", ContentType="audio/wav", ) s3_audio_file = f"{bucket}/test_torch_audio_s3/class={ref_label}/amazing_sound.wav" @@ -196,6 +199,7 @@ def test_torch_audio_s3(bucket): loader = DataLoader(ds, batch_size=1) for (audio, rate), label in loader: assert audio.shape == torch.Size((1, *size)) + wr.s3.delete_objects(path=path) # def test_torch_s3_file_dataset(bucket): @@ -212,7 +216,7 @@ def test_torch_audio_s3(bucket): @pytest.mark.parametrize("drop_last", [True, False]) def test_torch_s3_iterable(bucket, drop_last): - folder = "test_torch_s3_iterable" + folder = f"test_torch_s3_iterable_{str(drop_last).lower()}" path = f"s3://{bucket}/{folder}/" wr.s3.delete_objects(path=path) batch_size = 32 @@ -230,7 +234,7 @@ def test_torch_s3_iterable(bucket, drop_last): for image in DataLoader( wr.torch.S3IterableDataset( - path=f"s3://{bucket}/{folder}", + path=f"s3://{bucket}/{folder}/file", ), batch_size=batch_size, drop_last=drop_last, @@ -240,10 +244,12 @@ def test_torch_s3_iterable(bucket, drop_last): else: assert image[0].shape == torch.Size([3, 32, 32]) + wr.s3.delete_objects(path=path) + @pytest.mark.parametrize("drop_last", [True, False]) def test_torch_s3_iterable_with_labels(bucket, drop_last): - folder = "test_torch_s3_iterable_with_labels" + folder = f"test_torch_s3_iterable_with_labels_{str(drop_last).lower()}" path = f"s3://{bucket}/{folder}/" wr.s3.delete_objects(path=path) batch_size = 32 @@ -264,7 +270,7 @@ def test_torch_s3_iterable_with_labels(bucket, drop_last): for images, labels in DataLoader( wr.torch.S3IterableDataset( - path=f"s3://{bucket}/{folder}", + path=f"s3://{bucket}/{folder}/file", ), batch_size=batch_size, drop_last=drop_last, @@ -278,3 +284,6 @@ def test_torch_s3_iterable_with_labels(bucket, drop_last): assert images[0].shape == torch.Size([3, 32, 32]) assert labels[0].dtype == torch.int64 assert labels[0].shape == torch.Size([]) + + wr.s3.delete_objects(path=path) + From c091fa82e39e58375f5ea92527ed619c467ca974 Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Thu, 23 Apr 2020 22:23:55 -0300 Subject: [PATCH 21/27] fix lint --- awswrangler/torch.py | 102 +++++++++---------------- requirements-torch.txt | 3 +- testing/test_awswrangler/test_torch.py | 42 ++++------ 3 files changed, 52 insertions(+), 95 deletions(-) diff --git a/awswrangler/torch.py b/awswrangler/torch.py index c25e145ee..a5b589386 100644 --- a/awswrangler/torch.py +++ b/awswrangler/torch.py @@ -1,11 +1,11 @@ """PyTorch Module.""" -import logging import io +import logging import os -import tarfile import pathlib import re -from collections import Iterable +import tarfile +from collections.abc import Iterable from io import BytesIO from typing import Any, Callable, Iterator, List, Optional, Tuple, Union @@ -49,8 +49,8 @@ def __init__( path=path, suffix=suffix, boto3_session=self._session ) - def _fetch_data(self, path: str): - """Add parquet and csv support""" + def _fetch_data(self, path: str) -> Any: + """Add parquet and csv support.""" bucket, key = _utils.parse_path(path=path) buff = BytesIO() client_s3: boto3.client = _utils.client(service_name="s3", session=self._session) @@ -59,42 +59,23 @@ def _fetch_data(self, path: str): return buff @staticmethod - def _load_data(data: io.BytesIO, path: str): - if path.endswith('.tar.gz') or path.endswith('.tgz'): - pass - # tarfile.open(fileobj=data) + def _load_data(data: io.BytesIO, path: str) -> Any: + if path.endswith(".pt"): + data = torch.load(data) + elif path.endswith(".tar.gz") or path.endswith(".tgz"): + tarfile.open(fileobj=data) + raise NotImplementedError("Tar loader not implemented!") # tar = tarfile.open(fileobj=data) # for member in tar.getmembers(): - # print('member', member) - elif path.endswith('.pt'): - data = torch.load(data) + else: + raise NotImplementedError() + return data class _ListS3Dataset(_BaseS3Dataset, Dataset): """PyTorch Amazon S3 Map-Style List Dataset.""" - def __init__( - self, path: Union[str, List[str]], suffix: Optional[str] = None, boto3_session: Optional[boto3.Session] = None - ): - """PyTorch Map-Style List S3 Dataset. - - Each file under path would be handle as a single tensor. - - Parameters - ---------- - path : Union[str, List[str]] - S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). - boto3_session : boto3.Session(), optional - Boto3 Session. The default boto3 session will be used if boto3_session receive None. - - Returns - ------- - torch.utils.data.Dataset - - """ - super(_ListS3Dataset, self).__init__(path, suffix, boto3_session) - def __getitem__(self, index): path = self._paths[index] data = self._fetch_data(path) @@ -103,10 +84,10 @@ def __getitem__(self, index): def __len__(self): return len(self._paths) - def _data_fn(self, data): + def _data_fn(self, data) -> Any: pass - def _label_fn(self, path: str): + def _label_fn(self, path: str) -> Any: pass @@ -115,7 +96,7 @@ class _S3PartitionedDataset(_ListS3Dataset): def _label_fn(self, path: str) -> torch.Tensor: label = int(re.findall(r"/(.*?)=(.*?)/", path)[-1][1]) - return torch.tensor([label]) + return torch.tensor([label]) # pylint: disable=not-callable # class S3FilesDataset(_BaseS3Dataset, Dataset): @@ -135,7 +116,8 @@ def _label_fn(self, path: str) -> torch.Tensor: # Parameters # ---------- # path : Union[str, List[str]] -# S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). +# S3 prefix (e.g. s3://bucket/prefix) or +# list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). # boto3_session : boto3.Session(), optional # Boto3 Session. The default boto3 session will be used if boto3_session receive None. # @@ -227,7 +209,6 @@ def __init__( Note ---- - This dataset assumes audio files are stored with the following structure: @@ -254,7 +235,6 @@ def __init__( Examples -------- - Create a Audio S3 Dataset >>> import awswrangler as wr @@ -349,43 +329,35 @@ def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session: boto """ super(ImageS3Dataset, self).__init__(path, suffix, boto3_session) - def _data_fn(self, data: io.BytesIO) -> torch.Tensor: + def _data_fn(self, data: io.BytesIO) -> Any: image = Image.open(data) tensor = to_tensor(image) return tensor -class S3IterableDataset(_BaseS3Dataset, IterableDataset): - """PyTorch Amazon S3 Iterable Dataset.""" - - def __init__( - self, - path: Union[str, List[str]], - suffix: Optional[str] = None, - boto3_session: Optional[boto3.Session] = None, - ): - """PyTorch Amazon S3 Iterable Dataset. +class S3IterableDataset(IterableDataset, _BaseS3Dataset): # pylint: disable=abstract-method + """PyTorch Amazon S3 Iterable Dataset. - Parameters - ---------- - path : Union[str, List[str]] - S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). - boto3_session : boto3.Session(), optional - Boto3 Session. The default boto3 session will be used if boto3_session receive None. + Parameters + ---------- + path : Union[str, List[str]] + S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + boto3_session : boto3.Session(), optional + Boto3 Session. The default boto3 session will be used if boto3_session receive None. - Returns - ------- - torch.utils.data.Dataset + Returns + ------- + torch.utils.data.Dataset - Examples - -------- - >>> import awswrangler as wr - >>> ds = wr.torch.S3IterableDataset('s3://bucket/path') + Examples + -------- + >>> import awswrangler as wr + >>> ds = wr.torch.S3IterableDataset('s3://bucket/path') - """ - super(S3IterableDataset, self).__init__(path, suffix, boto3_session) + """ def __iter__(self) -> Union[Iterator[torch.Tensor], Iterator[Tuple[torch.Tensor, torch.Tensor]]]: + """Iterate over data returning tensors or expanding Iterables.""" for path in self._paths: data = self._fetch_data(path) data = self._load_data(data, path) diff --git a/requirements-torch.txt b/requirements-torch.txt index 325196f07..01d2c6e65 100644 --- a/requirements-torch.txt +++ b/requirements-torch.txt @@ -1,3 +1,4 @@ torch~=1.4.0 torchvision~=0.5.0 -torchaudio~=0.4.0 \ No newline at end of file +torchaudio~=0.4.0 +Pillow==7.1.1 diff --git a/testing/test_awswrangler/test_torch.py b/testing/test_awswrangler/test_torch.py index 40ecf7050..19a300400 100644 --- a/testing/test_awswrangler/test_torch.py +++ b/testing/test_awswrangler/test_torch.py @@ -1,6 +1,6 @@ import io -import re import logging +import re import boto3 import numpy as np @@ -128,8 +128,8 @@ def test_torch_image_s3(bucket): @pytest.mark.parametrize("drop_last", [True, False]) -def test_torch_image_s3(bucket, drop_last): - folder = f"test_torch_image_s3_{str(drop_last).lower()}" +def test_torch_image_s3_loader(bucket, drop_last): + folder = f"test_torch_image_s3_loader_{str(drop_last).lower()}" path = f"s3://{bucket}/{folder}/" wr.s3.delete_objects(path=path) client_s3 = boto3.client("s3") @@ -146,7 +146,11 @@ def test_torch_image_s3(bucket, drop_last): num_train = len(ds) indices = list(range(num_train)) loader = DataLoader( - ds, batch_size=batch_size, num_workers=4, sampler=torch.utils.data.sampler.RandomSampler(indices), drop_last=drop_last + ds, + batch_size=batch_size, + num_workers=4, + sampler=torch.utils.data.sampler.RandomSampler(indices), + drop_last=drop_last, ) for i, (image, label) in enumerate(loader): assert image.shape == torch.Size([batch_size, 4, 494, 1636]) @@ -226,18 +230,10 @@ def test_torch_s3_iterable(bucket, drop_last): buff = io.BytesIO() torch.save(batch, buff) buff.seek(0) - client_s3.put_object( - Body=buff.read(), - Bucket=bucket, - Key=f"{folder}/file{i}.pt", - ) + client_s3.put_object(Body=buff.read(), Bucket=bucket, Key=f"{folder}/file{i}.pt") for image in DataLoader( - wr.torch.S3IterableDataset( - path=f"s3://{bucket}/{folder}/file", - ), - batch_size=batch_size, - drop_last=drop_last, + wr.torch.S3IterableDataset(path=f"s3://{bucket}/{folder}/file"), batch_size=batch_size, drop_last=drop_last ): if drop_last: assert image.shape == torch.Size([batch_size, 3, 32, 32]) @@ -255,25 +251,14 @@ def test_torch_s3_iterable_with_labels(bucket, drop_last): batch_size = 32 client_s3 = boto3.client("s3") for i in range(3): - batch = ( - torch.randn(100, 3, 32, 32), - torch.randint(2, size=(100,)), - ) + batch = (torch.randn(100, 3, 32, 32), torch.randint(2, size=(100,))) buff = io.BytesIO() torch.save(batch, buff) buff.seek(0) - client_s3.put_object( - Body=buff.read(), - Bucket=bucket, - Key=f"{folder}/file{i}.pt", - ) + client_s3.put_object(Body=buff.read(), Bucket=bucket, Key=f"{folder}/file{i}.pt") for images, labels in DataLoader( - wr.torch.S3IterableDataset( - path=f"s3://{bucket}/{folder}/file", - ), - batch_size=batch_size, - drop_last=drop_last, + wr.torch.S3IterableDataset(path=f"s3://{bucket}/{folder}/file"), batch_size=batch_size, drop_last=drop_last ): if drop_last: assert images.shape == torch.Size([batch_size, 3, 32, 32]) @@ -286,4 +271,3 @@ def test_torch_s3_iterable_with_labels(bucket, drop_last): assert labels[0].shape == torch.Size([]) wr.s3.delete_objects(path=path) - From 37b7f1e7edf9aa233d07bfd06baa92db80dc7cc3 Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Fri, 24 Apr 2020 13:43:47 -0300 Subject: [PATCH 22/27] update readme --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index d4a8a3cad..624ebc12c 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ df = wr.db.read_sql_query("SELECT * FROM external_schema.my_table", con=engine) - [11 - CSV Datasets](https://github.com/awslabs/aws-data-wrangler/blob/master/tutorials/11%20-%20CSV%20Datasets.ipynb) - [12 - CSV Crawler](https://github.com/awslabs/aws-data-wrangler/blob/master/tutorials/12%20-%20CSV%20Crawler.ipynb) - [13 - Merging Datasets on S3](https://github.com/awslabs/aws-data-wrangler/blob/master/tutorials/13%20-%20Merging%20Datasets%20on%20S3.ipynb) + - [14 - PyTorch](https://github.com/awslabs/aws-data-wrangler/blob/master/tutorials/14%20-%20PyTorch.ipynb) - [**API Reference**](https://aws-data-wrangler.readthedocs.io/en/latest/api.html) - [Amazon S3](https://aws-data-wrangler.readthedocs.io/en/latest/api.html#amazon-s3) - [AWS Glue Catalog](https://aws-data-wrangler.readthedocs.io/en/latest/api.html#aws-glue-catalog) From 33d74c4354ebfffd357c6730b0cacbc727d33185 Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Fri, 24 Apr 2020 14:00:21 -0300 Subject: [PATCH 23/27] remove captalized requirement from docstring --- .github/workflows/static-checking.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/static-checking.yml b/.github/workflows/static-checking.yml index bc33d9327..9f0701146 100644 --- a/.github/workflows/static-checking.yml +++ b/.github/workflows/static-checking.yml @@ -30,7 +30,7 @@ jobs: - name: CloudFormation Lint run: cfn-lint -t testing/cloudformation.yaml - name: Documentation Lint - run: pydocstyle awswrangler/ --add-ignore=D204 + run: pydocstyle awswrangler/ --add-ignore=D204,D403 - name: mypy check run: mypy awswrangler - name: Flake8 Lint From 4b05b36575237da68de61335d6f5db8777e5f2cc Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Fri, 24 Apr 2020 14:12:26 -0300 Subject: [PATCH 24/27] add torch requirements --- .github/workflows/static-checking.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/static-checking.yml b/.github/workflows/static-checking.yml index 9f0701146..56f978a50 100644 --- a/.github/workflows/static-checking.yml +++ b/.github/workflows/static-checking.yml @@ -27,6 +27,7 @@ jobs: python -m pip install --upgrade pip pip install -r requirements.txt pip install -r requirements-dev.txt + pip install -r requirements-torch.txt - name: CloudFormation Lint run: cfn-lint -t testing/cloudformation.yaml - name: Documentation Lint From 86cdb307a27c7a6107627e34272da857c52573bf Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Sun, 26 Apr 2020 17:49:00 -0300 Subject: [PATCH 25/27] fix init and docs --- awswrangler/__init__.py | 11 ++++++++++- awswrangler/torch.py | 27 +++++++++++++++++++++++---- requirements-torch.txt | 4 ++-- 3 files changed, 35 insertions(+), 7 deletions(-) diff --git a/awswrangler/__init__.py b/awswrangler/__init__.py index ff6a2bd71..b7f931a3d 100644 --- a/awswrangler/__init__.py +++ b/awswrangler/__init__.py @@ -5,9 +5,18 @@ """ +import importlib import logging -from awswrangler import athena, catalog, cloudwatch, db, emr, exceptions, s3, torch # noqa +from awswrangler import athena, catalog, cloudwatch, db, emr, exceptions, s3 # noqa from awswrangler.__metadata__ import __description__, __license__, __title__, __version__ # noqa +if ( + importlib.util.find_spec("torch") + and importlib.util.find_spec("torchvision") + and importlib.util.find_spec("torchaudio") + and importlib.util.find_spec("PIL") +): # type: ignore + from awswrangler import torch # noqa + logging.getLogger("awswrangler").addHandler(logging.NullHandler()) diff --git a/awswrangler/torch.py b/awswrangler/torch.py index a5b589386..e7cd4518f 100644 --- a/awswrangler/torch.py +++ b/awswrangler/torch.py @@ -35,6 +35,8 @@ def __init__( ---------- path : Union[str, List[str]] S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + suffix: str, optional + S3 suffix filtering of object keys (i.e. suffix=".png" -> s3://*.png). boto3_session : boto3.Session(), optional Boto3 Session. The default boto3 session will be used if boto3_session receive None. @@ -85,10 +87,10 @@ def __len__(self): return len(self._paths) def _data_fn(self, data) -> Any: - pass + raise NotImplementedError() def _label_fn(self, path: str) -> Any: - pass + raise NotImplementedError() class _S3PartitionedDataset(_ListS3Dataset): @@ -98,6 +100,9 @@ def _label_fn(self, path: str) -> torch.Tensor: label = int(re.findall(r"/(.*?)=(.*?)/", path)[-1][1]) return torch.tensor([label]) # pylint: disable=not-callable + def _data_fn(self, data) -> Any: + raise NotImplementedError() + # class S3FilesDataset(_BaseS3Dataset, Dataset): # """PyTorch Amazon S3 Files Map-Style Dataset.""" @@ -162,6 +167,12 @@ def __init__( ---------- path : Union[str, List[str]] S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + data_fn: Callable + Function that receives a io.BytesIO object and returns a torch.Tensor + label_fn: Callable + Function that receives object path (str) and return a torch.Tensor + suffix: str, optional + S3 suffix filtering of object keys (i.e. suffix=".png" -> s3://*.png). boto3_session : boto3.Session(), optional Boto3 Session. The default boto3 session will be used if boto3_session receive None. @@ -226,6 +237,8 @@ def __init__( ---------- path : Union[str, List[str]] S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + suffix: str, optional + S3 suffix filtering of object keys (i.e. suffix=".png" -> s3://*.png). boto3_session : boto3.Session(), optional Boto3 Session. The default boto3 session will be used if boto3_session receive None. @@ -314,6 +327,8 @@ def __init__(self, path: Union[str, List[str]], suffix: str, boto3_session: boto ---------- path : Union[str, List[str]] S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + suffix: str, optional + S3 suffix filtering of object keys (i.e. suffix=".png" -> s3://*.png). boto3_session : boto3.Session(), optional Boto3 Session. The default boto3 session will be used if boto3_session receive None. @@ -342,6 +357,8 @@ class S3IterableDataset(IterableDataset, _BaseS3Dataset): # pylint: disable=abs ---------- path : Union[str, List[str]] S3 prefix (e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]). + suffix: str, optional + S3 suffix filtering of object keys (i.e. suffix=".png" -> s3://*.png). boto3_session : boto3.Session(), optional Boto3 Session. The default boto3 session will be used if boto3_session receive None. @@ -395,7 +412,9 @@ def __init__( SQLAlchemy Engine. Please use, wr.db.get_engine(), wr.db.get_redshift_temp_engine() or wr.catalog.get_engine() label_col : int, optional - Label column number + Label column number. + chunksize : int, optional + The chunksize determines que number of rows to be retrived from the database at each time. Returns ------- @@ -425,7 +444,7 @@ def __iter__(self) -> Union[Iterator[torch.Tensor], Iterator[Tuple[torch.Tensor, label_col: Optional[int] = list(cursor.keys()).index(self._label_col) else: label_col = self._label_col - _logger.debug(f"label_col: {label_col}") + _logger.debug("label_col: %s", label_col) if self._chunksize is None: return SQLDataset._records2tensor(records=cursor.fetchall(), label_col=label_col) return self._iterate_cursor(cursor=cursor, chunksize=self._chunksize, label_col=label_col) diff --git a/requirements-torch.txt b/requirements-torch.txt index 01d2c6e65..61de25397 100644 --- a/requirements-torch.txt +++ b/requirements-torch.txt @@ -1,4 +1,4 @@ -torch~=1.4.0 +torch~=1.5.0 torchvision~=0.5.0 torchaudio~=0.4.0 -Pillow==7.1.1 +Pillow~=7.1.1 From b3c8c811282f8d50fc3a7fa855ab7a0933e8d121 Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Sun, 26 Apr 2020 20:11:44 -0300 Subject: [PATCH 26/27] update tutorial --- tutorials/14 - PyTorch.ipynb | 121 ++++++++++++++++++++--------------- 1 file changed, 70 insertions(+), 51 deletions(-) diff --git a/tutorials/14 - PyTorch.ipynb b/tutorials/14 - PyTorch.ipynb index a3d988881..b85596986 100644 --- a/tutorials/14 - PyTorch.ipynb +++ b/tutorials/14 - PyTorch.ipynb @@ -19,24 +19,28 @@ "metadata": {}, "source": [ "## Table of Contents\n", - "* [1.Defining Training Function](#1.-Defininf-Training-Function)\n", - "* [2.Traning From Amazon S3](#1.-Traning-From-Amazon-S3)\n", - "\t* [2.1 Writing PyTorch Dataset to S3](#1.1-Writing-PyTorch-Dataset-to-S3)\n", - "\t* [2.2 Training Network](#1.2-Training-Network)\n", - "* [3. Training From SQL Query](#2.-Training-From-SQL-Query)\n", - "\t* [3.1 Writing Data to SQL Database](#2.1-Writing-Data-to-SQL-Database)\n", - "\t* [3.3 Training Network From SQL](#2.2-Reading-single-JSON-file)\n", - "* [4. Creating Custom S3 Dataset](#1.-Creating-Custom-S3-Dataset)\n", - "\t* [4.1 Creating Custom PyTorch Dataset](#1.1-Creating-Custom-PyTorch-Dataset)\n", - "\t* [4.2 Writing Data to S3](#1.1-Writing-Data-to-S3)\n", - "\t* [4.3 Training Network](#1.2-Training-Network)\n", - "* [5. Delete objects](#6.-Delete-objects)" + "* [1.Defining Training Function](#1.-Defining-Training-Function)\n", + "* [2.Training From Amazon S3](#2.-Traoning-From-Amazon-S3)\n", + "\t* [2.1 Writing PyTorch Dataset to S3](#2.1-Writing-PyTorch-Dataset-to-S3)\n", + "\t* [2.2 Training Network](#2.2-Training-Network)\n", + "* [3. Training From SQL Query](#3.-Training-From-SQL-Query)\n", + "\t* [3.1 Writing Data to SQL Database](#3.1-Writing-Data-to-SQL-Database)\n", + "\t* [3.3 Training Network From SQL](#3.3-Reading-single-JSON-file)\n", + "* [4. Creating Custom S3 Dataset](#4.-Creating-Custom-S3-Dataset)\n", + "\t* [4.1 Creating Custom PyTorch Dataset](#4.1-Creating-Custom-PyTorch-Dataset)\n", + "\t* [4.2 Writing Data to S3](#4.2-Writing-Data-to-S3)\n", + "\t* [4.3 Training Network](#4.4-Training-Network)\n", + "* [5. Delete objects](#5.-Delete-objects)" ] }, { "cell_type": "code", "execution_count": 1, - "metadata": {}, + "metadata": { + "pycharm": { + "name": "#%%\n" + } + }, "outputs": [], "source": [ "import io\n", @@ -55,13 +59,17 @@ { "cell_type": "code", "execution_count": 2, - "metadata": {}, + "metadata": { + "pycharm": { + "name": "#%%\n" + } + }, "outputs": [ { - "name": "stdin", + "name": "stdout", "output_type": "stream", "text": [ - " ··········································\n" + "········\n" ] } ], @@ -116,13 +124,24 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "# 2. Traning From Amazon S3" + "# 2. Training From Amazon S3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2.1 Writing PyTorch Dataset to S3" ] }, { "cell_type": "code", "execution_count": 4, - "metadata": {}, + "metadata": { + "pycharm": { + "name": "#%%\n" + } + }, "outputs": [], "source": [ "client_s3 = boto3.client(\"s3\")\n", @@ -153,23 +172,23 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "batch: 0 loss: 7.0221 acc: 0.00\n", - "batch: 1 loss: 2.7788 acc: 23.44\n", - "batch: 2 loss: 0.9828 acc: 32.29\n", - "batch: 3 loss: 0.9414 acc: 39.45\n", - "batch: 4 loss: 1.0737 acc: 39.38\n", - "batch: 0 loss: 1.2178 acc: 50.00\n", - "batch: 1 loss: 1.4069 acc: 51.56\n", - "batch: 2 loss: 1.0783 acc: 52.08\n", - "batch: 3 loss: 0.9926 acc: 52.34\n", - "batch: 4 loss: 1.1111 acc: 49.06\n" + "batch: 0 loss: 7.0132 acc: 0.00\n", + "batch: 1 loss: 2.8764 acc: 21.09\n", + "batch: 2 loss: 0.9600 acc: 32.29\n", + "batch: 3 loss: 0.8676 acc: 36.33\n", + "batch: 4 loss: 1.1386 acc: 36.88\n", + "batch: 0 loss: 1.0754 acc: 51.56\n", + "batch: 1 loss: 1.4241 acc: 51.56\n", + "batch: 2 loss: 1.3019 acc: 51.04\n", + "batch: 3 loss: 0.8631 acc: 53.52\n", + "batch: 4 loss: 0.4252 acc: 54.38\n" ] } ], @@ -196,7 +215,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 7, "metadata": {}, "outputs": [], "source": [ @@ -226,28 +245,28 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "batch: 0 loss: 5.0253 acc: 50.00\n", - "batch: 1 loss: 21.3174 acc: 50.00\n", - "batch: 2 loss: 0.5061 acc: 66.67\n", - "batch: 0 loss: 1.2222 acc: 50.00\n", - "batch: 1 loss: 0.7075 acc: 50.00\n", - "batch: 2 loss: 0.7077 acc: 50.00\n", - "batch: 0 loss: 0.9302 acc: 50.00\n", - "batch: 1 loss: 0.6960 acc: 50.00\n", - "batch: 2 loss: 0.6018 acc: 66.67\n", - "batch: 0 loss: 1.1284 acc: 50.00\n", - "batch: 1 loss: 0.7077 acc: 50.00\n", - "batch: 2 loss: 0.6791 acc: 50.00\n", - "batch: 0 loss: 1.0030 acc: 50.00\n", - "batch: 1 loss: 0.7053 acc: 50.00\n", - "batch: 2 loss: 0.6318 acc: 50.00\n" + "batch: 0 loss: 8.8708 acc: 50.00\n", + "batch: 1 loss: 88.7789 acc: 50.00\n", + "batch: 2 loss: 0.8655 acc: 33.33\n", + "batch: 0 loss: 0.7036 acc: 50.00\n", + "batch: 1 loss: 0.7034 acc: 50.00\n", + "batch: 2 loss: 0.8447 acc: 33.33\n", + "batch: 0 loss: 0.7012 acc: 50.00\n", + "batch: 1 loss: 0.7010 acc: 50.00\n", + "batch: 2 loss: 0.8250 acc: 33.33\n", + "batch: 0 loss: 0.6992 acc: 50.00\n", + "batch: 1 loss: 0.6991 acc: 50.00\n", + "batch: 2 loss: 0.8063 acc: 33.33\n", + "batch: 0 loss: 0.6975 acc: 50.00\n", + "batch: 1 loss: 0.6974 acc: 50.00\n", + "batch: 2 loss: 0.7886 acc: 33.33\n" ] } ], @@ -279,7 +298,7 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 9, "metadata": {}, "outputs": [], "source": [ @@ -289,9 +308,9 @@ ], "metadata": { "kernelspec": { - "display_name": "conda_python3", + "display_name": "Python 3", "language": "python", - "name": "conda_python3" + "name": "python3" }, "language_info": { "codemirror_mode": { @@ -303,9 +322,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.6.5" + "version": "3.7.5" } }, "nbformat": 4, "nbformat_minor": 4 -} +} \ No newline at end of file From f6927a4e75ced46bb42192b28539bd6473cb5848 Mon Sep 17 00:00:00 2001 From: Luigi Tedesco Date: Sun, 26 Apr 2020 21:16:10 -0300 Subject: [PATCH 27/27] rollback pytorch==1.5.0, due to torchaudio requirement --- requirements-torch.txt | 2 +- tutorials/14 - PyTorch.ipynb | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/requirements-torch.txt b/requirements-torch.txt index 61de25397..73b8aae36 100644 --- a/requirements-torch.txt +++ b/requirements-torch.txt @@ -1,4 +1,4 @@ -torch~=1.5.0 +torch~=1.4.0 torchvision~=0.5.0 torchaudio~=0.4.0 Pillow~=7.1.1 diff --git a/tutorials/14 - PyTorch.ipynb b/tutorials/14 - PyTorch.ipynb index b85596986..b7af04627 100644 --- a/tutorials/14 - PyTorch.ipynb +++ b/tutorials/14 - PyTorch.ipynb @@ -222,7 +222,7 @@ "eng = wr.catalog.get_engine(\"aws-data-wrangler-redshift\")\n", "df = pd.DataFrame({\n", " \"height\": [2, 1.4, 1.7, 1.8, 1.9, 2.2],\n", - " \"weigth\": [100.0, 50.0, 70.0, 80.0, 90.0, 160.0],\n", + " \"weight\": [100.0, 50.0, 70.0, 80.0, 90.0, 160.0],\n", " \"target\": [1, 0, 0, 1, 1, 1]\n", "})\n", "\n", @@ -302,7 +302,7 @@ "metadata": {}, "outputs": [], "source": [ - "wr.s3.delete_objects(f\"s3://{bucket}/\")" + "wr.s3.delete_objects(f\"s3://{bucket}/{folder}\")" ] } ],