Repository files navigation

TestDeepSource

%matplotlibinlineimportmatplotlib.pyplotaspltimporttorch.utils.dataimporttorch.nnfromrandomimportrandrangeimportosos.environ["WDS_VERBOSE_CACHE"] ="1"os.environ["GOPEN_VERBOSE"] ="0"

The WebDataset Format

WebDataset format files are tar files, with two conventions:

  • within each tar file, files that belong together and make up a training sample share the same basename when stripped of all filename extensions
  • the shards of a tar file are numbered like something-000000.tar to something-012345.tar, usually specified using brace notation something-{000000..012345}.tar

You can find a longer, more detailed specification of the WebDataset format in the WebDataset Format Specification

WebDataset can read files from local disk or from any pipe, which allows it to access files using common cloud object stores. WebDataset can also read concatenated MsgPack and CBORs sources.

The WebDataset representation allows writing purely sequential I/O pipelines for large scale deep learning. This is important for achieving high I/O rates from local storage (3x-10x for local drives compared to random access) and for using object stores and cloud storage for training.

The WebDataset format represents images, movies, audio, etc. in their native file formats, making the creation of WebDataset format data as easy as just creating a tar archive. Because of the way data is aligned, WebDataset works well with block deduplication as well and aligns data on predictable boundaries.

Standard tools can be used for accessing and processing WebDataset-format files.

bucket="https://storage.googleapis.com/webdataset/testdata/"dataset="publaynet-train-{000000..000009}.tar"url=bucket+dataset
!curl-s {bucket}publaynet-train-000000.tar|ddcount=50002>/dev/null|tartf-2>/dev/null|sed10q
PMC4991227_00003.json
PMC4991227_00003.png
PMC4537884_00002.json
PMC4537884_00002.png
PMC4323233_00003.json
PMC4323233_00003.png
PMC5429906_00004.json
PMC5429906_00004.png
PMC5592712_00002.json
PMC5592712_00002.png

Note that in these .tar files, we have pairs of .json and .png files; each such pair makes up a training sample.

WebDataset Libraries

There are several libraries supporting the WebDataset format:

  • webdataset for Python3 (includes the wids library), this repository
  • Webdataset.jl a Julia implementation
  • tarp, a Golang implementation and command line tool
  • Ray Data sources and sinks

The webdataset library can be used with PyTorch, Tensorflow, and Jax.

The webdataset Library

The webdataset library is an implementation of PyTorch IterableDataset (or a mock implementation thereof if you aren't using PyTorch). It implements as form of stream processing. Some of its features are:

  • large scale parallel data access through sharding
  • high performance disk I/O due to purely sequential reads
  • latency insensitive due to big fat pipes
  • no local storage required
  • instant startup for training jobs
  • only requires reading from file descriptors/network streams, no special APIs
  • its API encourages high performance I/O pipelines
  • scalable from tiny desktop datasets to petascale datasets
  • provides local caching if desired
  • requires no dataset metadata; any collection of shards can be read and used instantly

The main limitations people run into are related to the fact that IterableDataset is less commonly used in PyTorch and some existing code may not support it as well, and that achieving an exactly balanced number of training samples across many compute nodes for a fixed epoch size is tricky; for multinode training, webdataset is usually used with shard resampling.

There are two interfaces, the concise "fluid" interface and a longer "pipeline" interface. We'll show examples using the fluid interface, which is usually what you want.

importwebdatasetaswdsshuffle_buffer=10# usually, pick something bigger, like 1000pil_dataset=wds.WebDataset(url).shuffle(shuffle_buffer).decode("pil").to_tuple("png", "json")
/Users/tbreuel/proj/webdataset/src/webdataset/compat.py:379: UserWarning: WebDataset(shardshuffle=...) is None; set explicitly to False or a number
warnings.warn("WebDataset(shardshuffle=...) is None; set explicitly to False or a number")

The resulting datasets are standard PyTorch IterableDataset instances.

isinstance(pil_dataset, torch.utils.data.IterableDataset)
True
forimage, jsoninpil_dataset:
breakplt.imshow(image)
<matplotlib.image.AxesImage at 0x12fec5050>

png

We can add onto the existing pipeline for augmentation and data preparation.

importtorchvision.transformsastransformsfromPILimportImagepreproc=transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
lambdax: 1-x,
])
defpreprocess(sample):
image, json=sampletry:
label=json["annotations"][0]["category_id"]
exceptException:
label=0returnpreproc(image), labeldataset=pil_dataset.map(preprocess)
forimage, labelindataset:
breakplt.imshow(image.numpy().transpose(1, 2, 0))
<matplotlib.image.AxesImage at 0x1677a1250>

png

WebDataset is just an instance of a standard IterableDataset. It's a single-threaded way of iterating over a dataset. Since image decompression and data augmentation can be compute intensive, PyTorch usually uses the DataLoader class to parallelize data loading and preprocessing. WebDataset is fully compatible with the standard DataLoader.

Here are a number of notebooks showing how to use WebDataset for image classification and LLM training:

The wds-notes notebook contains some additional documentation and information about the library.

The webdataset Pipeline API

The wds.WebDataset fluid interface is just a convenient shorthand for writing down pipelines. The underlying pipeline is an instance of the wds.DataPipeline class, and you can construct data pipelines explicitly, similar to the way you use nn.Sequential inside models.

dataset=wds.DataPipeline(
wds.SimpleShardList(url),
# at this point we have an iterator over all the shards# this shuffles the shardswds.shuffle(100),
# add wds.split_by_node here if you are using multiple nodeswds.split_by_worker,
# at this point, we have an iterator over the shards assigned to each workerwds.tarfile_to_samples(),
# this shuffles the samples in memorywds.shuffle(shuffle_buffer),
# this decodes the images and jsonwds.decode("pil"),
wds.to_tuple("png", "json"),
wds.map(preprocess),
wds.batched(16)
)
batch=next(iter(dataset))
batch[0].shape, batch[1].shape
(torch.Size([16, 3, 224, 224]), (16,))

Secure Mode

You can run WebDataset in a mode that improves security. This disables the pipe: and file: protocols, as well as attempts to decode Python pickles. This should disable simple attacks and no successful attacks are currently known; rely on this mode at your own risk.

You enable secure mode by setting webdataset.utils.enforce_security = True before you start using the library. You can also set WDS_SECURE=1 in your environment.

Installation and Documentation

$ pip install webdataset

For the Github version:

$ pip install git+https://github.com/tmbdev/webdataset.git

Here are some videos talking about WebDataset and large scale deep learning:

Dependencies

The WebDataset library only requires PyTorch, NumPy, and a small library called braceexpand.

WebDataset loads a few additional libraries dynamically only when they are actually needed and only in the decoder:

  • PIL/Pillow for image decoding
  • torchvision, torchvideo, torchaudio for image/video/audio decoding
  • msgpack for MessagePack decoding
  • the curl command line tool for accessing HTTP servers
  • the Google/Amazon/Azure command line tools for accessing cloud storage buckets

Loading of one of these libraries is triggered by configuring a decoder that attempts to decode content in the given format and encountering a file in that format during decoding. (Eventually, the torch... dependencies will be refactored into those libraries.)

About

A high-performance Python-based I/O system for large (and small) deep learning problems, with strong support for PyTorch.

Topics

Resources

Stars

3.2k stars

Watchers

21 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

TestDeepSource

%matplotlibinlineimportmatplotlib.pyplotaspltimporttorch.utils.dataimporttorch.nnfromrandomimportrandrangeimportosos.environ["WDS_VERBOSE_CACHE"] ="1"os.environ["GOPEN_VERBOSE"] ="0"

The WebDataset Format

WebDataset format files are tar files, with two conventions:

  • within each tar file, files that belong together and make up a training sample share the same basename when stripped of all filename extensions
  • the shards of a tar file are numbered like something-000000.tar to something-012345.tar, usually specified using brace notation something-{000000..012345}.tar

You can find a longer, more detailed specification of the WebDataset format in the WebDataset Format Specification

WebDataset can read files from local disk or from any pipe, which allows it to access files using common cloud object stores. WebDataset can also read concatenated MsgPack and CBORs sources.

The WebDataset representation allows writing purely sequential I/O pipelines for large scale deep learning. This is important for achieving high I/O rates from local storage (3x-10x for local drives compared to random access) and for using object stores and cloud storage for training.

The WebDataset format represents images, movies, audio, etc. in their native file formats, making the creation of WebDataset format data as easy as just creating a tar archive. Because of the way data is aligned, WebDataset works well with block deduplication as well and aligns data on predictable boundaries.

Standard tools can be used for accessing and processing WebDataset-format files.

bucket="https://storage.googleapis.com/webdataset/testdata/"dataset="publaynet-train-{000000..000009}.tar"url=bucket+dataset
!curl-s {bucket}publaynet-train-000000.tar|ddcount=50002>/dev/null|tartf-2>/dev/null|sed10q
PMC4991227_00003.json
PMC4991227_00003.png
PMC4537884_00002.json
PMC4537884_00002.png
PMC4323233_00003.json
PMC4323233_00003.png
PMC5429906_00004.json
PMC5429906_00004.png
PMC5592712_00002.json
PMC5592712_00002.png

Note that in these .tar files, we have pairs of .json and .png files; each such pair makes up a training sample.

WebDataset Libraries

There are several libraries supporting the WebDataset format:

  • webdataset for Python3 (includes the wids library), this repository
  • Webdataset.jl a Julia implementation
  • tarp, a Golang implementation and command line tool
  • Ray Data sources and sinks

The webdataset library can be used with PyTorch, Tensorflow, and Jax.

The webdataset Library

The webdataset library is an implementation of PyTorch IterableDataset (or a mock implementation thereof if you aren't using PyTorch). It implements as form of stream processing. Some of its features are:

  • large scale parallel data access through sharding
  • high performance disk I/O due to purely sequential reads
  • latency insensitive due to big fat pipes
  • no local storage required
  • instant startup for training jobs
  • only requires reading from file descriptors/network streams, no special APIs
  • its API encourages high performance I/O pipelines
  • scalable from tiny desktop datasets to petascale datasets
  • provides local caching if desired
  • requires no dataset metadata; any collection of shards can be read and used instantly

The main limitations people run into are related to the fact that IterableDataset is less commonly used in PyTorch and some existing code may not support it as well, and that achieving an exactly balanced number of training samples across many compute nodes for a fixed epoch size is tricky; for multinode training, webdataset is usually used with shard resampling.

There are two interfaces, the concise "fluid" interface and a longer "pipeline" interface. We'll show examples using the fluid interface, which is usually what you want.

importwebdatasetaswdsshuffle_buffer=10# usually, pick something bigger, like 1000pil_dataset=wds.WebDataset(url).shuffle(shuffle_buffer).decode("pil").to_tuple("png", "json")
/Users/tbreuel/proj/webdataset/src/webdataset/compat.py:379: UserWarning: WebDataset(shardshuffle=...) is None; set explicitly to False or a number
warnings.warn("WebDataset(shardshuffle=...) is None; set explicitly to False or a number")

The resulting datasets are standard PyTorch IterableDataset instances.

isinstance(pil_dataset, torch.utils.data.IterableDataset)
True
forimage, jsoninpil_dataset:
breakplt.imshow(image)
<matplotlib.image.AxesImage at 0x12fec5050>

png

We can add onto the existing pipeline for augmentation and data preparation.

importtorchvision.transformsastransformsfromPILimportImagepreproc=transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
lambdax: 1-x,
])
defpreprocess(sample):
image, json=sampletry:
label=json["annotations"][0]["category_id"]
exceptException:
label=0returnpreproc(image), labeldataset=pil_dataset.map(preprocess)
forimage, labelindataset:
breakplt.imshow(image.numpy().transpose(1, 2, 0))
<matplotlib.image.AxesImage at 0x1677a1250>

png

WebDataset is just an instance of a standard IterableDataset. It's a single-threaded way of iterating over a dataset. Since image decompression and data augmentation can be compute intensive, PyTorch usually uses the DataLoader class to parallelize data loading and preprocessing. WebDataset is fully compatible with the standard DataLoader.

Here are a number of notebooks showing how to use WebDataset for image classification and LLM training:

The wds-notes notebook contains some additional documentation and information about the library.

The webdataset Pipeline API

The wds.WebDataset fluid interface is just a convenient shorthand for writing down pipelines. The underlying pipeline is an instance of the wds.DataPipeline class, and you can construct data pipelines explicitly, similar to the way you use nn.Sequential inside models.

dataset=wds.DataPipeline(
wds.SimpleShardList(url),
# at this point we have an iterator over all the shards# this shuffles the shardswds.shuffle(100),
# add wds.split_by_node here if you are using multiple nodeswds.split_by_worker,
# at this point, we have an iterator over the shards assigned to each workerwds.tarfile_to_samples(),
# this shuffles the samples in memorywds.shuffle(shuffle_buffer),
# this decodes the images and jsonwds.decode("pil"),
wds.to_tuple("png", "json"),
wds.map(preprocess),
wds.batched(16)
)
batch=next(iter(dataset))
batch[0].shape, batch[1].shape
(torch.Size([16, 3, 224, 224]), (16,))

Secure Mode

You can run WebDataset in a mode that improves security. This disables the pipe: and file: protocols, as well as attempts to decode Python pickles. This should disable simple attacks and no successful attacks are currently known; rely on this mode at your own risk.

You enable secure mode by setting webdataset.utils.enforce_security = True before you start using the library. You can also set WDS_SECURE=1 in your environment.

Installation and Documentation

$ pip install webdataset

For the Github version:

$ pip install git+https://github.com/tmbdev/webdataset.git

Here are some videos talking about WebDataset and large scale deep learning:

Dependencies

The WebDataset library only requires PyTorch, NumPy, and a small library called braceexpand.

WebDataset loads a few additional libraries dynamically only when they are actually needed and only in the decoder:

  • PIL/Pillow for image decoding
  • torchvision, torchvideo, torchaudio for image/video/audio decoding
  • msgpack for MessagePack decoding
  • the curl command line tool for accessing HTTP servers
  • the Google/Amazon/Azure command line tools for accessing cloud storage buckets

Loading of one of these libraries is triggered by configuring a decoder that attempts to decode content in the given format and encountering a file in that format during decoding. (Eventually, the torch... dependencies will be refactored into those libraries.)

About

A high-performance Python-based I/O system for large (and small) deep learning problems, with strong support for PyTorch.

Topics

Resources

Stars

3.2k stars

Watchers

21 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

TestDeepSource

%matplotlibinlineimportmatplotlib.pyplotaspltimporttorch.utils.dataimporttorch.nnfromrandomimportrandrangeimportosos.environ["WDS_VERBOSE_CACHE"] ="1"os.environ["GOPEN_VERBOSE"] ="0"

The WebDataset Format

WebDataset format files are tar files, with two conventions:

  • within each tar file, files that belong together and make up a training sample share the same basename when stripped of all filename extensions
  • the shards of a tar file are numbered like something-000000.tar to something-012345.tar, usually specified using brace notation something-{000000..012345}.tar

You can find a longer, more detailed specification of the WebDataset format in the WebDataset Format Specification

WebDataset can read files from local disk or from any pipe, which allows it to access files using common cloud object stores. WebDataset can also read concatenated MsgPack and CBORs sources.

The WebDataset representation allows writing purely sequential I/O pipelines for large scale deep learning. This is important for achieving high I/O rates from local storage (3x-10x for local drives compared to random access) and for using object stores and cloud storage for training.

The WebDataset format represents images, movies, audio, etc. in their native file formats, making the creation of WebDataset format data as easy as just creating a tar archive. Because of the way data is aligned, WebDataset works well with block deduplication as well and aligns data on predictable boundaries.

Standard tools can be used for accessing and processing WebDataset-format files.

bucket="https://storage.googleapis.com/webdataset/testdata/"dataset="publaynet-train-{000000..000009}.tar"url=bucket+dataset
!curl-s {bucket}publaynet-train-000000.tar|ddcount=50002>/dev/null|tartf-2>/dev/null|sed10q
PMC4991227_00003.json
PMC4991227_00003.png
PMC4537884_00002.json
PMC4537884_00002.png
PMC4323233_00003.json
PMC4323233_00003.png
PMC5429906_00004.json
PMC5429906_00004.png
PMC5592712_00002.json
PMC5592712_00002.png

Note that in these .tar files, we have pairs of .json and .png files; each such pair makes up a training sample.

WebDataset Libraries

There are several libraries supporting the WebDataset format:

  • webdataset for Python3 (includes the wids library), this repository
  • Webdataset.jl a Julia implementation
  • tarp, a Golang implementation and command line tool
  • Ray Data sources and sinks

The webdataset library can be used with PyTorch, Tensorflow, and Jax.

The webdataset Library

The webdataset library is an implementation of PyTorch IterableDataset (or a mock implementation thereof if you aren't using PyTorch). It implements as form of stream processing. Some of its features are:

  • large scale parallel data access through sharding
  • high performance disk I/O due to purely sequential reads
  • latency insensitive due to big fat pipes
  • no local storage required
  • instant startup for training jobs
  • only requires reading from file descriptors/network streams, no special APIs
  • its API encourages high performance I/O pipelines
  • scalable from tiny desktop datasets to petascale datasets
  • provides local caching if desired
  • requires no dataset metadata; any collection of shards can be read and used instantly

The main limitations people run into are related to the fact that IterableDataset is less commonly used in PyTorch and some existing code may not support it as well, and that achieving an exactly balanced number of training samples across many compute nodes for a fixed epoch size is tricky; for multinode training, webdataset is usually used with shard resampling.

There are two interfaces, the concise "fluid" interface and a longer "pipeline" interface. We'll show examples using the fluid interface, which is usually what you want.

importwebdatasetaswdsshuffle_buffer=10# usually, pick something bigger, like 1000pil_dataset=wds.WebDataset(url).shuffle(shuffle_buffer).decode("pil").to_tuple("png", "json")
/Users/tbreuel/proj/webdataset/src/webdataset/compat.py:379: UserWarning: WebDataset(shardshuffle=...) is None; set explicitly to False or a number
warnings.warn("WebDataset(shardshuffle=...) is None; set explicitly to False or a number")

The resulting datasets are standard PyTorch IterableDataset instances.

isinstance(pil_dataset, torch.utils.data.IterableDataset)
True
forimage, jsoninpil_dataset:
breakplt.imshow(image)
<matplotlib.image.AxesImage at 0x12fec5050>

png

We can add onto the existing pipeline for augmentation and data preparation.

importtorchvision.transformsastransformsfromPILimportImagepreproc=transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
lambdax: 1-x,
])
defpreprocess(sample):
image, json=sampletry:
label=json["annotations"][0]["category_id"]
exceptException:
label=0returnpreproc(image), labeldataset=pil_dataset.map(preprocess)
forimage, labelindataset:
breakplt.imshow(image.numpy().transpose(1, 2, 0))
<matplotlib.image.AxesImage at 0x1677a1250>

png

WebDataset is just an instance of a standard IterableDataset. It's a single-threaded way of iterating over a dataset. Since image decompression and data augmentation can be compute intensive, PyTorch usually uses the DataLoader class to parallelize data loading and preprocessing. WebDataset is fully compatible with the standard DataLoader.

Here are a number of notebooks showing how to use WebDataset for image classification and LLM training:

The wds-notes notebook contains some additional documentation and information about the library.

The webdataset Pipeline API

The wds.WebDataset fluid interface is just a convenient shorthand for writing down pipelines. The underlying pipeline is an instance of the wds.DataPipeline class, and you can construct data pipelines explicitly, similar to the way you use nn.Sequential inside models.

dataset=wds.DataPipeline(
wds.SimpleShardList(url),
# at this point we have an iterator over all the shards# this shuffles the shardswds.shuffle(100),
# add wds.split_by_node here if you are using multiple nodeswds.split_by_worker,
# at this point, we have an iterator over the shards assigned to each workerwds.tarfile_to_samples(),
# this shuffles the samples in memorywds.shuffle(shuffle_buffer),
# this decodes the images and jsonwds.decode("pil"),
wds.to_tuple("png", "json"),
wds.map(preprocess),
wds.batched(16)
)
batch=next(iter(dataset))
batch[0].shape, batch[1].shape
(torch.Size([16, 3, 224, 224]), (16,))

Secure Mode

You can run WebDataset in a mode that improves security. This disables the pipe: and file: protocols, as well as attempts to decode Python pickles. This should disable simple attacks and no successful attacks are currently known; rely on this mode at your own risk.

You enable secure mode by setting webdataset.utils.enforce_security = True before you start using the library. You can also set WDS_SECURE=1 in your environment.

Installation and Documentation

$ pip install webdataset

For the Github version:

$ pip install git+https://github.com/tmbdev/webdataset.git

Here are some videos talking about WebDataset and large scale deep learning:

Dependencies

The WebDataset library only requires PyTorch, NumPy, and a small library called braceexpand.

WebDataset loads a few additional libraries dynamically only when they are actually needed and only in the decoder:

  • PIL/Pillow for image decoding
  • torchvision, torchvideo, torchaudio for image/video/audio decoding
  • msgpack for MessagePack decoding
  • the curl command line tool for accessing HTTP servers
  • the Google/Amazon/Azure command line tools for accessing cloud storage buckets

Loading of one of these libraries is triggered by configuring a decoder that attempts to decode content in the given format and encountering a file in that format during decoding. (Eventually, the torch... dependencies will be refactored into those libraries.)

About

A high-performance Python-based I/O system for large (and small) deep learning problems, with strong support for PyTorch.

Topics

Resources

Stars

3.2k stars

Watchers

21 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

TestDeepSource

%matplotlibinlineimportmatplotlib.pyplotaspltimporttorch.utils.dataimporttorch.nnfromrandomimportrandrangeimportosos.environ["WDS_VERBOSE_CACHE"] ="1"os.environ["GOPEN_VERBOSE"] ="0"

The WebDataset Format

WebDataset format files are tar files, with two conventions:

  • within each tar file, files that belong together and make up a training sample share the same basename when stripped of all filename extensions
  • the shards of a tar file are numbered like something-000000.tar to something-012345.tar, usually specified using brace notation something-{000000..012345}.tar

You can find a longer, more detailed specification of the WebDataset format in the WebDataset Format Specification

WebDataset can read files from local disk or from any pipe, which allows it to access files using common cloud object stores. WebDataset can also read concatenated MsgPack and CBORs sources.

The WebDataset representation allows writing purely sequential I/O pipelines for large scale deep learning. This is important for achieving high I/O rates from local storage (3x-10x for local drives compared to random access) and for using object stores and cloud storage for training.

The WebDataset format represents images, movies, audio, etc. in their native file formats, making the creation of WebDataset format data as easy as just creating a tar archive. Because of the way data is aligned, WebDataset works well with block deduplication as well and aligns data on predictable boundaries.

Standard tools can be used for accessing and processing WebDataset-format files.

bucket="https://storage.googleapis.com/webdataset/testdata/"dataset="publaynet-train-{000000..000009}.tar"url=bucket+dataset
!curl-s {bucket}publaynet-train-000000.tar|ddcount=50002>/dev/null|tartf-2>/dev/null|sed10q
PMC4991227_00003.json
PMC4991227_00003.png
PMC4537884_00002.json
PMC4537884_00002.png
PMC4323233_00003.json
PMC4323233_00003.png
PMC5429906_00004.json
PMC5429906_00004.png
PMC5592712_00002.json
PMC5592712_00002.png

Note that in these .tar files, we have pairs of .json and .png files; each such pair makes up a training sample.

WebDataset Libraries

There are several libraries supporting the WebDataset format:

  • webdataset for Python3 (includes the wids library), this repository
  • Webdataset.jl a Julia implementation
  • tarp, a Golang implementation and command line tool
  • Ray Data sources and sinks

The webdataset library can be used with PyTorch, Tensorflow, and Jax.

The webdataset Library

The webdataset library is an implementation of PyTorch IterableDataset (or a mock implementation thereof if you aren't using PyTorch). It implements as form of stream processing. Some of its features are:

  • large scale parallel data access through sharding
  • high performance disk I/O due to purely sequential reads
  • latency insensitive due to big fat pipes
  • no local storage required
  • instant startup for training jobs
  • only requires reading from file descriptors/network streams, no special APIs
  • its API encourages high performance I/O pipelines
  • scalable from tiny desktop datasets to petascale datasets
  • provides local caching if desired
  • requires no dataset metadata; any collection of shards can be read and used instantly

The main limitations people run into are related to the fact that IterableDataset is less commonly used in PyTorch and some existing code may not support it as well, and that achieving an exactly balanced number of training samples across many compute nodes for a fixed epoch size is tricky; for multinode training, webdataset is usually used with shard resampling.

There are two interfaces, the concise "fluid" interface and a longer "pipeline" interface. We'll show examples using the fluid interface, which is usually what you want.

importwebdatasetaswdsshuffle_buffer=10# usually, pick something bigger, like 1000pil_dataset=wds.WebDataset(url).shuffle(shuffle_buffer).decode("pil").to_tuple("png", "json")
/Users/tbreuel/proj/webdataset/src/webdataset/compat.py:379: UserWarning: WebDataset(shardshuffle=...) is None; set explicitly to False or a number
warnings.warn("WebDataset(shardshuffle=...) is None; set explicitly to False or a number")

The resulting datasets are standard PyTorch IterableDataset instances.

isinstance(pil_dataset, torch.utils.data.IterableDataset)
True
forimage, jsoninpil_dataset:
breakplt.imshow(image)
<matplotlib.image.AxesImage at 0x12fec5050>

png

We can add onto the existing pipeline for augmentation and data preparation.

importtorchvision.transformsastransformsfromPILimportImagepreproc=transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
lambdax: 1-x,
])
defpreprocess(sample):
image, json=sampletry:
label=json["annotations"][0]["category_id"]
exceptException:
label=0returnpreproc(image), labeldataset=pil_dataset.map(preprocess)
forimage, labelindataset:
breakplt.imshow(image.numpy().transpose(1, 2, 0))
<matplotlib.image.AxesImage at 0x1677a1250>

png

WebDataset is just an instance of a standard IterableDataset. It's a single-threaded way of iterating over a dataset. Since image decompression and data augmentation can be compute intensive, PyTorch usually uses the DataLoader class to parallelize data loading and preprocessing. WebDataset is fully compatible with the standard DataLoader.

Here are a number of notebooks showing how to use WebDataset for image classification and LLM training:

The wds-notes notebook contains some additional documentation and information about the library.

The webdataset Pipeline API

The wds.WebDataset fluid interface is just a convenient shorthand for writing down pipelines. The underlying pipeline is an instance of the wds.DataPipeline class, and you can construct data pipelines explicitly, similar to the way you use nn.Sequential inside models.

dataset=wds.DataPipeline(
wds.SimpleShardList(url),
# at this point we have an iterator over all the shards# this shuffles the shardswds.shuffle(100),
# add wds.split_by_node here if you are using multiple nodeswds.split_by_worker,
# at this point, we have an iterator over the shards assigned to each workerwds.tarfile_to_samples(),
# this shuffles the samples in memorywds.shuffle(shuffle_buffer),
# this decodes the images and jsonwds.decode("pil"),
wds.to_tuple("png", "json"),
wds.map(preprocess),
wds.batched(16)
)
batch=next(iter(dataset))
batch[0].shape, batch[1].shape
(torch.Size([16, 3, 224, 224]), (16,))

Secure Mode

You can run WebDataset in a mode that improves security. This disables the pipe: and file: protocols, as well as attempts to decode Python pickles. This should disable simple attacks and no successful attacks are currently known; rely on this mode at your own risk.

You enable secure mode by setting webdataset.utils.enforce_security = True before you start using the library. You can also set WDS_SECURE=1 in your environment.

Installation and Documentation

$ pip install webdataset

For the Github version:

$ pip install git+https://github.com/tmbdev/webdataset.git

Here are some videos talking about WebDataset and large scale deep learning:

Dependencies

The WebDataset library only requires PyTorch, NumPy, and a small library called braceexpand.

WebDataset loads a few additional libraries dynamically only when they are actually needed and only in the decoder:

  • PIL/Pillow for image decoding
  • torchvision, torchvideo, torchaudio for image/video/audio decoding
  • msgpack for MessagePack decoding
  • the curl command line tool for accessing HTTP servers
  • the Google/Amazon/Azure command line tools for accessing cloud storage buckets

Loading of one of these libraries is triggered by configuring a decoder that attempts to decode content in the given format and encountering a file in that format during decoding. (Eventually, the torch... dependencies will be refactored into those libraries.)

About

A high-performance Python-based I/O system for large (and small) deep learning problems, with strong support for PyTorch.

Topics

Resources

Stars

3.2k stars

Watchers

21 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

TestDeepSource

%matplotlibinlineimportmatplotlib.pyplotaspltimporttorch.utils.dataimporttorch.nnfromrandomimportrandrangeimportosos.environ["WDS_VERBOSE_CACHE"] ="1"os.environ["GOPEN_VERBOSE"] ="0"

The WebDataset Format

WebDataset format files are tar files, with two conventions:

  • within each tar file, files that belong together and make up a training sample share the same basename when stripped of all filename extensions
  • the shards of a tar file are numbered like something-000000.tar to something-012345.tar, usually specified using brace notation something-{000000..012345}.tar

You can find a longer, more detailed specification of the WebDataset format in the WebDataset Format Specification

WebDataset can read files from local disk or from any pipe, which allows it to access files using common cloud object stores. WebDataset can also read concatenated MsgPack and CBORs sources.

The WebDataset representation allows writing purely sequential I/O pipelines for large scale deep learning. This is important for achieving high I/O rates from local storage (3x-10x for local drives compared to random access) and for using object stores and cloud storage for training.

The WebDataset format represents images, movies, audio, etc. in their native file formats, making the creation of WebDataset format data as easy as just creating a tar archive. Because of the way data is aligned, WebDataset works well with block deduplication as well and aligns data on predictable boundaries.

Standard tools can be used for accessing and processing WebDataset-format files.

bucket="https://storage.googleapis.com/webdataset/testdata/"dataset="publaynet-train-{000000..000009}.tar"url=bucket+dataset
!curl-s {bucket}publaynet-train-000000.tar|ddcount=50002>/dev/null|tartf-2>/dev/null|sed10q
PMC4991227_00003.json
PMC4991227_00003.png
PMC4537884_00002.json
PMC4537884_00002.png
PMC4323233_00003.json
PMC4323233_00003.png
PMC5429906_00004.json
PMC5429906_00004.png
PMC5592712_00002.json
PMC5592712_00002.png

Note that in these .tar files, we have pairs of .json and .png files; each such pair makes up a training sample.

WebDataset Libraries

There are several libraries supporting the WebDataset format:

  • webdataset for Python3 (includes the wids library), this repository
  • Webdataset.jl a Julia implementation
  • tarp, a Golang implementation and command line tool
  • Ray Data sources and sinks

The webdataset library can be used with PyTorch, Tensorflow, and Jax.

The webdataset Library

The webdataset library is an implementation of PyTorch IterableDataset (or a mock implementation thereof if you aren't using PyTorch). It implements as form of stream processing. Some of its features are:

  • large scale parallel data access through sharding
  • high performance disk I/O due to purely sequential reads
  • latency insensitive due to big fat pipes
  • no local storage required
  • instant startup for training jobs
  • only requires reading from file descriptors/network streams, no special APIs
  • its API encourages high performance I/O pipelines
  • scalable from tiny desktop datasets to petascale datasets
  • provides local caching if desired
  • requires no dataset metadata; any collection of shards can be read and used instantly

The main limitations people run into are related to the fact that IterableDataset is less commonly used in PyTorch and some existing code may not support it as well, and that achieving an exactly balanced number of training samples across many compute nodes for a fixed epoch size is tricky; for multinode training, webdataset is usually used with shard resampling.

There are two interfaces, the concise "fluid" interface and a longer "pipeline" interface. We'll show examples using the fluid interface, which is usually what you want.

importwebdatasetaswdsshuffle_buffer=10# usually, pick something bigger, like 1000pil_dataset=wds.WebDataset(url).shuffle(shuffle_buffer).decode("pil").to_tuple("png", "json")
/Users/tbreuel/proj/webdataset/src/webdataset/compat.py:379: UserWarning: WebDataset(shardshuffle=...) is None; set explicitly to False or a number
warnings.warn("WebDataset(shardshuffle=...) is None; set explicitly to False or a number")

The resulting datasets are standard PyTorch IterableDataset instances.

isinstance(pil_dataset, torch.utils.data.IterableDataset)
True
forimage, jsoninpil_dataset:
breakplt.imshow(image)
<matplotlib.image.AxesImage at 0x12fec5050>

png

We can add onto the existing pipeline for augmentation and data preparation.

importtorchvision.transformsastransformsfromPILimportImagepreproc=transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
lambdax: 1-x,
])
defpreprocess(sample):
image, json=sampletry:
label=json["annotations"][0]["category_id"]
exceptException:
label=0returnpreproc(image), labeldataset=pil_dataset.map(preprocess)
forimage, labelindataset:
breakplt.imshow(image.numpy().transpose(1, 2, 0))
<matplotlib.image.AxesImage at 0x1677a1250>

png

WebDataset is just an instance of a standard IterableDataset. It's a single-threaded way of iterating over a dataset. Since image decompression and data augmentation can be compute intensive, PyTorch usually uses the DataLoader class to parallelize data loading and preprocessing. WebDataset is fully compatible with the standard DataLoader.

Here are a number of notebooks showing how to use WebDataset for image classification and LLM training:

The wds-notes notebook contains some additional documentation and information about the library.

The webdataset Pipeline API

The wds.WebDataset fluid interface is just a convenient shorthand for writing down pipelines. The underlying pipeline is an instance of the wds.DataPipeline class, and you can construct data pipelines explicitly, similar to the way you use nn.Sequential inside models.

dataset=wds.DataPipeline(
wds.SimpleShardList(url),
# at this point we have an iterator over all the shards# this shuffles the shardswds.shuffle(100),
# add wds.split_by_node here if you are using multiple nodeswds.split_by_worker,
# at this point, we have an iterator over the shards assigned to each workerwds.tarfile_to_samples(),
# this shuffles the samples in memorywds.shuffle(shuffle_buffer),
# this decodes the images and jsonwds.decode("pil"),
wds.to_tuple("png", "json"),
wds.map(preprocess),
wds.batched(16)
)
batch=next(iter(dataset))
batch[0].shape, batch[1].shape
(torch.Size([16, 3, 224, 224]), (16,))

Secure Mode

You can run WebDataset in a mode that improves security. This disables the pipe: and file: protocols, as well as attempts to decode Python pickles. This should disable simple attacks and no successful attacks are currently known; rely on this mode at your own risk.

You enable secure mode by setting webdataset.utils.enforce_security = True before you start using the library. You can also set WDS_SECURE=1 in your environment.

Installation and Documentation

$ pip install webdataset

For the Github version:

$ pip install git+https://github.com/tmbdev/webdataset.git

Here are some videos talking about WebDataset and large scale deep learning:

Dependencies

The WebDataset library only requires PyTorch, NumPy, and a small library called braceexpand.

WebDataset loads a few additional libraries dynamically only when they are actually needed and only in the decoder:

  • PIL/Pillow for image decoding
  • torchvision, torchvideo, torchaudio for image/video/audio decoding
  • msgpack for MessagePack decoding
  • the curl command line tool for accessing HTTP servers
  • the Google/Amazon/Azure command line tools for accessing cloud storage buckets

Loading of one of these libraries is triggered by configuring a decoder that attempts to decode content in the given format and encountering a file in that format during decoding. (Eventually, the torch... dependencies will be refactored into those libraries.)

About

A high-performance Python-based I/O system for large (and small) deep learning problems, with strong support for PyTorch.

Topics

Resources

Stars

3.2k stars

Watchers

21 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

TestDeepSource

%matplotlibinlineimportmatplotlib.pyplotaspltimporttorch.utils.dataimporttorch.nnfromrandomimportrandrangeimportosos.environ["WDS_VERBOSE_CACHE"] ="1"os.environ["GOPEN_VERBOSE"] ="0"

The WebDataset Format

WebDataset format files are tar files, with two conventions:

  • within each tar file, files that belong together and make up a training sample share the same basename when stripped of all filename extensions
  • the shards of a tar file are numbered like something-000000.tar to something-012345.tar, usually specified using brace notation something-{000000..012345}.tar

You can find a longer, more detailed specification of the WebDataset format in the WebDataset Format Specification

WebDataset can read files from local disk or from any pipe, which allows it to access files using common cloud object stores. WebDataset can also read concatenated MsgPack and CBORs sources.

The WebDataset representation allows writing purely sequential I/O pipelines for large scale deep learning. This is important for achieving high I/O rates from local storage (3x-10x for local drives compared to random access) and for using object stores and cloud storage for training.

The WebDataset format represents images, movies, audio, etc. in their native file formats, making the creation of WebDataset format data as easy as just creating a tar archive. Because of the way data is aligned, WebDataset works well with block deduplication as well and aligns data on predictable boundaries.

Standard tools can be used for accessing and processing WebDataset-format files.

bucket="https://storage.googleapis.com/webdataset/testdata/"dataset="publaynet-train-{000000..000009}.tar"url=bucket+dataset
!curl-s {bucket}publaynet-train-000000.tar|ddcount=50002>/dev/null|tartf-2>/dev/null|sed10q
PMC4991227_00003.json
PMC4991227_00003.png
PMC4537884_00002.json
PMC4537884_00002.png
PMC4323233_00003.json
PMC4323233_00003.png
PMC5429906_00004.json
PMC5429906_00004.png
PMC5592712_00002.json
PMC5592712_00002.png

Note that in these .tar files, we have pairs of .json and .png files; each such pair makes up a training sample.

WebDataset Libraries

There are several libraries supporting the WebDataset format:

  • webdataset for Python3 (includes the wids library), this repository
  • Webdataset.jl a Julia implementation
  • tarp, a Golang implementation and command line tool
  • Ray Data sources and sinks

The webdataset library can be used with PyTorch, Tensorflow, and Jax.

The webdataset Library

The webdataset library is an implementation of PyTorch IterableDataset (or a mock implementation thereof if you aren't using PyTorch). It implements as form of stream processing. Some of its features are:

  • large scale parallel data access through sharding
  • high performance disk I/O due to purely sequential reads
  • latency insensitive due to big fat pipes
  • no local storage required
  • instant startup for training jobs
  • only requires reading from file descriptors/network streams, no special APIs
  • its API encourages high performance I/O pipelines
  • scalable from tiny desktop datasets to petascale datasets
  • provides local caching if desired
  • requires no dataset metadata; any collection of shards can be read and used instantly

The main limitations people run into are related to the fact that IterableDataset is less commonly used in PyTorch and some existing code may not support it as well, and that achieving an exactly balanced number of training samples across many compute nodes for a fixed epoch size is tricky; for multinode training, webdataset is usually used with shard resampling.

There are two interfaces, the concise "fluid" interface and a longer "pipeline" interface. We'll show examples using the fluid interface, which is usually what you want.

importwebdatasetaswdsshuffle_buffer=10# usually, pick something bigger, like 1000pil_dataset=wds.WebDataset(url).shuffle(shuffle_buffer).decode("pil").to_tuple("png", "json")
/Users/tbreuel/proj/webdataset/src/webdataset/compat.py:379: UserWarning: WebDataset(shardshuffle=...) is None; set explicitly to False or a number
warnings.warn("WebDataset(shardshuffle=...) is None; set explicitly to False or a number")

The resulting datasets are standard PyTorch IterableDataset instances.

isinstance(pil_dataset, torch.utils.data.IterableDataset)
True
forimage, jsoninpil_dataset:
breakplt.imshow(image)
<matplotlib.image.AxesImage at 0x12fec5050>

png

We can add onto the existing pipeline for augmentation and data preparation.

importtorchvision.transformsastransformsfromPILimportImagepreproc=transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
lambdax: 1-x,
])
defpreprocess(sample):
image, json=sampletry:
label=json["annotations"][0]["category_id"]
exceptException:
label=0returnpreproc(image), labeldataset=pil_dataset.map(preprocess)
forimage, labelindataset:
breakplt.imshow(image.numpy().transpose(1, 2, 0))
<matplotlib.image.AxesImage at 0x1677a1250>

png

WebDataset is just an instance of a standard IterableDataset. It's a single-threaded way of iterating over a dataset. Since image decompression and data augmentation can be compute intensive, PyTorch usually uses the DataLoader class to parallelize data loading and preprocessing. WebDataset is fully compatible with the standard DataLoader.

Here are a number of notebooks showing how to use WebDataset for image classification and LLM training:

The wds-notes notebook contains some additional documentation and information about the library.

The webdataset Pipeline API

The wds.WebDataset fluid interface is just a convenient shorthand for writing down pipelines. The underlying pipeline is an instance of the wds.DataPipeline class, and you can construct data pipelines explicitly, similar to the way you use nn.Sequential inside models.

dataset=wds.DataPipeline(
wds.SimpleShardList(url),
# at this point we have an iterator over all the shards# this shuffles the shardswds.shuffle(100),
# add wds.split_by_node here if you are using multiple nodeswds.split_by_worker,
# at this point, we have an iterator over the shards assigned to each workerwds.tarfile_to_samples(),
# this shuffles the samples in memorywds.shuffle(shuffle_buffer),
# this decodes the images and jsonwds.decode("pil"),
wds.to_tuple("png", "json"),
wds.map(preprocess),
wds.batched(16)
)
batch=next(iter(dataset))
batch[0].shape, batch[1].shape
(torch.Size([16, 3, 224, 224]), (16,))

Secure Mode

You can run WebDataset in a mode that improves security. This disables the pipe: and file: protocols, as well as attempts to decode Python pickles. This should disable simple attacks and no successful attacks are currently known; rely on this mode at your own risk.

You enable secure mode by setting webdataset.utils.enforce_security = True before you start using the library. You can also set WDS_SECURE=1 in your environment.

Installation and Documentation

$ pip install webdataset

For the Github version:

$ pip install git+https://github.com/tmbdev/webdataset.git

Here are some videos talking about WebDataset and large scale deep learning:

Dependencies

The WebDataset library only requires PyTorch, NumPy, and a small library called braceexpand.

WebDataset loads a few additional libraries dynamically only when they are actually needed and only in the decoder:

  • PIL/Pillow for image decoding
  • torchvision, torchvideo, torchaudio for image/video/audio decoding
  • msgpack for MessagePack decoding
  • the curl command line tool for accessing HTTP servers
  • the Google/Amazon/Azure command line tools for accessing cloud storage buckets

Loading of one of these libraries is triggered by configuring a decoder that attempts to decode content in the given format and encountering a file in that format during decoding. (Eventually, the torch... dependencies will be refactored into those libraries.)

About

A high-performance Python-based I/O system for large (and small) deep learning problems, with strong support for PyTorch.

Topics

Resources

Stars

3.2k stars

Watchers

21 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

TestDeepSource

%matplotlibinlineimportmatplotlib.pyplotaspltimporttorch.utils.dataimporttorch.nnfromrandomimportrandrangeimportosos.environ["WDS_VERBOSE_CACHE"] ="1"os.environ["GOPEN_VERBOSE"] ="0"

The WebDataset Format

WebDataset format files are tar files, with two conventions:

  • within each tar file, files that belong together and make up a training sample share the same basename when stripped of all filename extensions
  • the shards of a tar file are numbered like something-000000.tar to something-012345.tar, usually specified using brace notation something-{000000..012345}.tar

You can find a longer, more detailed specification of the WebDataset format in the WebDataset Format Specification

WebDataset can read files from local disk or from any pipe, which allows it to access files using common cloud object stores. WebDataset can also read concatenated MsgPack and CBORs sources.

The WebDataset representation allows writing purely sequential I/O pipelines for large scale deep learning. This is important for achieving high I/O rates from local storage (3x-10x for local drives compared to random access) and for using object stores and cloud storage for training.

The WebDataset format represents images, movies, audio, etc. in their native file formats, making the creation of WebDataset format data as easy as just creating a tar archive. Because of the way data is aligned, WebDataset works well with block deduplication as well and aligns data on predictable boundaries.

Standard tools can be used for accessing and processing WebDataset-format files.

bucket="https://storage.googleapis.com/webdataset/testdata/"dataset="publaynet-train-{000000..000009}.tar"url=bucket+dataset
!curl-s {bucket}publaynet-train-000000.tar|ddcount=50002>/dev/null|tartf-2>/dev/null|sed10q
PMC4991227_00003.json
PMC4991227_00003.png
PMC4537884_00002.json
PMC4537884_00002.png
PMC4323233_00003.json
PMC4323233_00003.png
PMC5429906_00004.json
PMC5429906_00004.png
PMC5592712_00002.json
PMC5592712_00002.png

Note that in these .tar files, we have pairs of .json and .png files; each such pair makes up a training sample.

WebDataset Libraries

There are several libraries supporting the WebDataset format:

  • webdataset for Python3 (includes the wids library), this repository
  • Webdataset.jl a Julia implementation
  • tarp, a Golang implementation and command line tool
  • Ray Data sources and sinks

The webdataset library can be used with PyTorch, Tensorflow, and Jax.

The webdataset Library

The webdataset library is an implementation of PyTorch IterableDataset (or a mock implementation thereof if you aren't using PyTorch). It implements as form of stream processing. Some of its features are:

  • large scale parallel data access through sharding
  • high performance disk I/O due to purely sequential reads
  • latency insensitive due to big fat pipes
  • no local storage required
  • instant startup for training jobs
  • only requires reading from file descriptors/network streams, no special APIs
  • its API encourages high performance I/O pipelines
  • scalable from tiny desktop datasets to petascale datasets
  • provides local caching if desired
  • requires no dataset metadata; any collection of shards can be read and used instantly

The main limitations people run into are related to the fact that IterableDataset is less commonly used in PyTorch and some existing code may not support it as well, and that achieving an exactly balanced number of training samples across many compute nodes for a fixed epoch size is tricky; for multinode training, webdataset is usually used with shard resampling.

There are two interfaces, the concise "fluid" interface and a longer "pipeline" interface. We'll show examples using the fluid interface, which is usually what you want.

importwebdatasetaswdsshuffle_buffer=10# usually, pick something bigger, like 1000pil_dataset=wds.WebDataset(url).shuffle(shuffle_buffer).decode("pil").to_tuple("png", "json")
/Users/tbreuel/proj/webdataset/src/webdataset/compat.py:379: UserWarning: WebDataset(shardshuffle=...) is None; set explicitly to False or a number
warnings.warn("WebDataset(shardshuffle=...) is None; set explicitly to False or a number")

The resulting datasets are standard PyTorch IterableDataset instances.

isinstance(pil_dataset, torch.utils.data.IterableDataset)
True
forimage, jsoninpil_dataset:
breakplt.imshow(image)
<matplotlib.image.AxesImage at 0x12fec5050>

png

We can add onto the existing pipeline for augmentation and data preparation.

importtorchvision.transformsastransformsfromPILimportImagepreproc=transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
lambdax: 1-x,
])
defpreprocess(sample):
image, json=sampletry:
label=json["annotations"][0]["category_id"]
exceptException:
label=0returnpreproc(image), labeldataset=pil_dataset.map(preprocess)
forimage, labelindataset:
breakplt.imshow(image.numpy().transpose(1, 2, 0))
<matplotlib.image.AxesImage at 0x1677a1250>

png

WebDataset is just an instance of a standard IterableDataset. It's a single-threaded way of iterating over a dataset. Since image decompression and data augmentation can be compute intensive, PyTorch usually uses the DataLoader class to parallelize data loading and preprocessing. WebDataset is fully compatible with the standard DataLoader.

Here are a number of notebooks showing how to use WebDataset for image classification and LLM training:

The wds-notes notebook contains some additional documentation and information about the library.

The webdataset Pipeline API

The wds.WebDataset fluid interface is just a convenient shorthand for writing down pipelines. The underlying pipeline is an instance of the wds.DataPipeline class, and you can construct data pipelines explicitly, similar to the way you use nn.Sequential inside models.

dataset=wds.DataPipeline(
wds.SimpleShardList(url),
# at this point we have an iterator over all the shards# this shuffles the shardswds.shuffle(100),
# add wds.split_by_node here if you are using multiple nodeswds.split_by_worker,
# at this point, we have an iterator over the shards assigned to each workerwds.tarfile_to_samples(),
# this shuffles the samples in memorywds.shuffle(shuffle_buffer),
# this decodes the images and jsonwds.decode("pil"),
wds.to_tuple("png", "json"),
wds.map(preprocess),
wds.batched(16)
)
batch=next(iter(dataset))
batch[0].shape, batch[1].shape
(torch.Size([16, 3, 224, 224]), (16,))

Secure Mode

You can run WebDataset in a mode that improves security. This disables the pipe: and file: protocols, as well as attempts to decode Python pickles. This should disable simple attacks and no successful attacks are currently known; rely on this mode at your own risk.

You enable secure mode by setting webdataset.utils.enforce_security = True before you start using the library. You can also set WDS_SECURE=1 in your environment.

Installation and Documentation

$ pip install webdataset

For the Github version:

$ pip install git+https://github.com/tmbdev/webdataset.git

Here are some videos talking about WebDataset and large scale deep learning:

Dependencies

The WebDataset library only requires PyTorch, NumPy, and a small library called braceexpand.

WebDataset loads a few additional libraries dynamically only when they are actually needed and only in the decoder:

  • PIL/Pillow for image decoding
  • torchvision, torchvideo, torchaudio for image/video/audio decoding
  • msgpack for MessagePack decoding
  • the curl command line tool for accessing HTTP servers
  • the Google/Amazon/Azure command line tools for accessing cloud storage buckets

Loading of one of these libraries is triggered by configuring a decoder that attempts to decode content in the given format and encountering a file in that format during decoding. (Eventually, the torch... dependencies will be refactored into those libraries.)

About

A high-performance Python-based I/O system for large (and small) deep learning problems, with strong support for PyTorch.

Topics

Resources

Stars

3.2k stars

Watchers

21 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

TestDeepSource

%matplotlibinlineimportmatplotlib.pyplotaspltimporttorch.utils.dataimporttorch.nnfromrandomimportrandrangeimportosos.environ["WDS_VERBOSE_CACHE"] ="1"os.environ["GOPEN_VERBOSE"] ="0"

The WebDataset Format

WebDataset format files are tar files, with two conventions:

  • within each tar file, files that belong together and make up a training sample share the same basename when stripped of all filename extensions
  • the shards of a tar file are numbered like something-000000.tar to something-012345.tar, usually specified using brace notation something-{000000..012345}.tar

You can find a longer, more detailed specification of the WebDataset format in the WebDataset Format Specification

WebDataset can read files from local disk or from any pipe, which allows it to access files using common cloud object stores. WebDataset can also read concatenated MsgPack and CBORs sources.

The WebDataset representation allows writing purely sequential I/O pipelines for large scale deep learning. This is important for achieving high I/O rates from local storage (3x-10x for local drives compared to random access) and for using object stores and cloud storage for training.

The WebDataset format represents images, movies, audio, etc. in their native file formats, making the creation of WebDataset format data as easy as just creating a tar archive. Because of the way data is aligned, WebDataset works well with block deduplication as well and aligns data on predictable boundaries.

Standard tools can be used for accessing and processing WebDataset-format files.

bucket="https://storage.googleapis.com/webdataset/testdata/"dataset="publaynet-train-{000000..000009}.tar"url=bucket+dataset
!curl-s {bucket}publaynet-train-000000.tar|ddcount=50002>/dev/null|tartf-2>/dev/null|sed10q
PMC4991227_00003.json
PMC4991227_00003.png
PMC4537884_00002.json
PMC4537884_00002.png
PMC4323233_00003.json
PMC4323233_00003.png
PMC5429906_00004.json
PMC5429906_00004.png
PMC5592712_00002.json
PMC5592712_00002.png

Note that in these .tar files, we have pairs of .json and .png files; each such pair makes up a training sample.

WebDataset Libraries

There are several libraries supporting the WebDataset format:

  • webdataset for Python3 (includes the wids library), this repository
  • Webdataset.jl a Julia implementation
  • tarp, a Golang implementation and command line tool
  • Ray Data sources and sinks

The webdataset library can be used with PyTorch, Tensorflow, and Jax.

The webdataset Library

The webdataset library is an implementation of PyTorch IterableDataset (or a mock implementation thereof if you aren't using PyTorch). It implements as form of stream processing. Some of its features are:

  • large scale parallel data access through sharding
  • high performance disk I/O due to purely sequential reads
  • latency insensitive due to big fat pipes
  • no local storage required
  • instant startup for training jobs
  • only requires reading from file descriptors/network streams, no special APIs
  • its API encourages high performance I/O pipelines
  • scalable from tiny desktop datasets to petascale datasets
  • provides local caching if desired
  • requires no dataset metadata; any collection of shards can be read and used instantly

The main limitations people run into are related to the fact that IterableDataset is less commonly used in PyTorch and some existing code may not support it as well, and that achieving an exactly balanced number of training samples across many compute nodes for a fixed epoch size is tricky; for multinode training, webdataset is usually used with shard resampling.

There are two interfaces, the concise "fluid" interface and a longer "pipeline" interface. We'll show examples using the fluid interface, which is usually what you want.

importwebdatasetaswdsshuffle_buffer=10# usually, pick something bigger, like 1000pil_dataset=wds.WebDataset(url).shuffle(shuffle_buffer).decode("pil").to_tuple("png", "json")
/Users/tbreuel/proj/webdataset/src/webdataset/compat.py:379: UserWarning: WebDataset(shardshuffle=...) is None; set explicitly to False or a number
warnings.warn("WebDataset(shardshuffle=...) is None; set explicitly to False or a number")

The resulting datasets are standard PyTorch IterableDataset instances.

isinstance(pil_dataset, torch.utils.data.IterableDataset)
True
forimage, jsoninpil_dataset:
breakplt.imshow(image)
<matplotlib.image.AxesImage at 0x12fec5050>

png

We can add onto the existing pipeline for augmentation and data preparation.

importtorchvision.transformsastransformsfromPILimportImagepreproc=transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
lambdax: 1-x,
])
defpreprocess(sample):
image, json=sampletry:
label=json["annotations"][0]["category_id"]
exceptException:
label=0returnpreproc(image), labeldataset=pil_dataset.map(preprocess)
forimage, labelindataset:
breakplt.imshow(image.numpy().transpose(1, 2, 0))
<matplotlib.image.AxesImage at 0x1677a1250>

png

WebDataset is just an instance of a standard IterableDataset. It's a single-threaded way of iterating over a dataset. Since image decompression and data augmentation can be compute intensive, PyTorch usually uses the DataLoader class to parallelize data loading and preprocessing. WebDataset is fully compatible with the standard DataLoader.

Here are a number of notebooks showing how to use WebDataset for image classification and LLM training:

The wds-notes notebook contains some additional documentation and information about the library.

The webdataset Pipeline API

The wds.WebDataset fluid interface is just a convenient shorthand for writing down pipelines. The underlying pipeline is an instance of the wds.DataPipeline class, and you can construct data pipelines explicitly, similar to the way you use nn.Sequential inside models.

dataset=wds.DataPipeline(
wds.SimpleShardList(url),
# at this point we have an iterator over all the shards# this shuffles the shardswds.shuffle(100),
# add wds.split_by_node here if you are using multiple nodeswds.split_by_worker,
# at this point, we have an iterator over the shards assigned to each workerwds.tarfile_to_samples(),
# this shuffles the samples in memorywds.shuffle(shuffle_buffer),
# this decodes the images and jsonwds.decode("pil"),
wds.to_tuple("png", "json"),
wds.map(preprocess),
wds.batched(16)
)
batch=next(iter(dataset))
batch[0].shape, batch[1].shape
(torch.Size([16, 3, 224, 224]), (16,))

Secure Mode

You can run WebDataset in a mode that improves security. This disables the pipe: and file: protocols, as well as attempts to decode Python pickles. This should disable simple attacks and no successful attacks are currently known; rely on this mode at your own risk.

You enable secure mode by setting webdataset.utils.enforce_security = True before you start using the library. You can also set WDS_SECURE=1 in your environment.

Installation and Documentation

$ pip install webdataset

For the Github version:

$ pip install git+https://github.com/tmbdev/webdataset.git

Here are some videos talking about WebDataset and large scale deep learning:

Dependencies

The WebDataset library only requires PyTorch, NumPy, and a small library called braceexpand.

WebDataset loads a few additional libraries dynamically only when they are actually needed and only in the decoder:

  • PIL/Pillow for image decoding
  • torchvision, torchvideo, torchaudio for image/video/audio decoding
  • msgpack for MessagePack decoding
  • the curl command line tool for accessing HTTP servers
  • the Google/Amazon/Azure command line tools for accessing cloud storage buckets

Loading of one of these libraries is triggered by configuring a decoder that attempts to decode content in the given format and encountering a file in that format during decoding. (Eventually, the torch... dependencies will be refactored into those libraries.)

About

A high-performance Python-based I/O system for large (and small) deep learning problems, with strong support for PyTorch.

Topics

Resources

Stars

3.2k stars

Watchers

21 watching

Forks

Releases

Packages

Used by

Contributors

Languages