builder
data.batch_sampler.builder
BatchSampler
BatchSampler(dataset: Dataset, batch_size: int = 1, repeat: bool = False, shuffle: bool = False, drop_last: bool = False)
Bases: Registerable, ABC
Baseclass for all batch_sampler classes.
Attributes:
-
dataset(Dataset) –dataset to sample from.
-
batch_size(int) –batch size.
-
repeat(bool) –repeat data when data is not enough for batch size.
-
shuffle(bool) –shuffle data.
-
drop_last(bool) –drop last data when data is not enough for batch size.
Note
batch_size,shuffle, anddrop_lastshould be popped from dataloader config, then passed to the batch sampler config.repeat: for SaigeVision2 api, should be set asTrue.- if number of data is enough for batch size, then
repeatis neglected.
- if number of data is enough for batch size, then
drop_last: for SaigeVision2 api, should be set asTrue.- to prevent the last batch from being smaller than the specified batch size.
- if
False, even whenrepeatis set asTrue, the last batch will be smaller than the specified batch size.
- for Training,
shuffleshould be set asTrue.drop_lastandrepeatare optional.
- for Validation,
repeat,shuffle, anddrop_lastshould be set asFalse.
Examples:
>>> cfg_sampler.update(
... {
... "shuffle": cfg_dataloader.pop("shuffle", False),
... "drop_last": cfg_dataloader.pop("drop_last", False),
... "batch_size": cfg_dataloader.pop("batch_size", 1),
... }
... )
... batch_sampler = build_batch_sampler(dataset=dataset, **cfg_sampler)
... dataloader = build_dataloader(
... dataset,
... collate_fn=collate_fn,
... batch_sampler=batch_sampler,
... **cfg_dataloader,
... )
Source code in SaigeToolkit/data/batch_sampler/base_sampler.py
BalancedSampler
BalancedSampler(dataset: Dataset, balance_keys: Optional[List[str]] = None, balance_ratios: Optional[List[float]] = None, calculate_patch_number: bool = False, shuffle: bool = True, **kwargs)
Bases: BatchSampler
Sampler implementation for weighted API dataset balancing.
Sampler class is used to specify the sequence of indices/keys used in data loading. This class represents iterable objects over the indices to datasets.
When __iter__ is called, Sampler creates self.buffer, a sequence of data indices
which is balanced to has exact same number of data sample from each data subset.
If balance_ratio is given, sampler autmatically re-weights each subset. Otherwise,
each subset will be balanced to be equal size.
Attributes:
-
dataset(Dataset) –dataset instance to be sampled
-
calculate_patch_number(bool) –whether update number of patches in dataset, after sampling
-
subset_data_indices(List[List[int]]) –split data indices, based on subset descriminator
-
multipliers(ndarray) –number of repeats for each data subset
-
remainers(ndarray) –number of remainers for each data subset
-
shuffle(bool) –whether shuffle output data indices after sampling
-
buffer(ndarray) –data indices for one epoch (accept duplication)
Note
Given:
-
dataset: Dataset with number of sample 300. which can be splitted into two subsets using given key set[key_a, key_b].subset_a: Data subset with number of sample 100, corresponds tokey_a.subset_b: Data subset with number of sample 200, corresponds tokey_b.
The word
correspondsmeans that eachdomain,source, andcategoryvalue parsed from the key is same to that of metadata information of each data in subset.
Output:
iterator: An iterator with 200 indices from subset_a and 200 indices from subset_b. The max element of iterator will be 299, which is len(subset_a) + len(subset_b) - 1.
The iterator must be directly fed to torch.utils.data.DataLoader class initializer
with name sample, along with torch.utils.data.ApiDataset object.
Examples:
>>> loader = torch.utils.data.DataLoader(
... dataset=torch.utils.data.ApiDataset(...),
... shuffle=False,
... batch_sampler=BalancedDatasetSampler(
... dataset,
... balance_keys=["Document/AI_HUB", "Document/CJ"],
... balance_ratios=[0.6, 0.3],
... ),
... )
Reference: https://pytorch.org/docs/stable/data.html#data-loading-order-and-sampler
initializing balance sampler
Parameters:
-
dataset(Dataset) –dataset to be sampled. directly set to class attribute.
-
balance_keys(List[str], default:None) –domain-source-categoty keys as subset descriminator. Defaults to None.
-
balance_ratios(Optional[List[float]], default:None) –balance of subsets. if None, subsets are equally sampled. Defaults to None.
-
calculate_patch_number(bool, default:False) –boolean to calculate patch_number after sampling. directly set to class attribute. Defaults to False.
-
shuffle(bool, default:True) –boolean to shuffle data sample. Defaults to True.
Source code in SaigeToolkit/data/batch_sampler/balanced_sampler.py
_build_default_balance_keys
Build default balance_keys which is grouping all domain-source-category separately
Parameters:
-
dataset(Dataset) –dataset instance. should have
filesattribute (SaigeDataset). each file data should have domain, source, category information, which would be used as subset descriminator.
Returns:
-
List[str]–List[str]: balance_key list example: ["Document/AI_HUB", "Document/CJ"]
Source code in SaigeToolkit/data/batch_sampler/balanced_sampler.py
_extract_domain_source_category_from_key
A function that parses given key for balancing.
empty string between slash (/) or "None" string will be treated as None-key
This function assumes target key is in the form of ...
"{domain}" # or ... "{domain}/{source}" # or ... "{domain}/{source}/{category}" "''/None/{category}" (ex) "Document/AI_HUB/상.하수도관리"
Parameters:
-
key(str) –Key string for separating datasets into subsets.
Returns:
-
List[List[str]]–List[List[str]]: domain_source_category_list. Key string parsed into list.
-
List[List[str]]–(ex)
-
List[List[str]]–["Document", None, None]
-
List[List[str]]–["Document", "AI_HUB", None]
-
List[List[str]]–["Document", "AI_HUB", "상.하수도관리"]
-
List[List[str]]–[None, None, "상.하수도관리"]
Source code in SaigeToolkit/data/batch_sampler/balanced_sampler.py
_split_dataset_indices_using_keys
A function that splits dataset using given keys.
Each key contains metadata info: domain, source, and category.
This key information will be used to separate total dataset into specific subsets.
For each data in dataset, check whether data's domain, source, and category corresponds to the key information.
For example, if a key is given as below:
key = "sample_domain/sample_source/sample_category"
Then the subset will be generated containing only index of data with metadata of:
{ ... domain: "sample_domain", ... source: "sample_source", ... category: "sample_category", ... ... ... }
For another example, if a key is given as below:
key = "sample_domain"
Then the subset will be generated containing only index of data with metadata of:
{ ... domain: "sample_domain", ... ... ... }
This generation process will be repeated for each key in target_keys.
Parameters:
-
target_keys(List[str]) –List key for subset balancing.
Returns:
-
List[List[int]]–List[List[int]]: subset_data_indices. List of data index list. Each element represents a subset of dataset.
Source code in SaigeToolkit/data/batch_sampler/balanced_sampler.py
match_identifier
Check data identifier matches non-None target identifier identifier: [domain, source, category]
Parameters:
-
id_data(Optional[str]) –data item identifier
-
id_target(Optional[str]) –balance target subset identifier
Returns:
-
bool(bool) –whether id's are matched
Source code in SaigeToolkit/data/batch_sampler/balanced_sampler.py
_calculate_subset_weights
Calculate subset multiplier and remainer using following two variables: balance_ratios, subset_size_ratios
balance_ratios: resultant data exposure ratio by subsets subset_size_ratios: data sizes ratio between subsets
Parameters:
-
balance_ratios(ndarray) –resultant data exposure ratio by subsets
Source code in SaigeToolkit/data/batch_sampler/balanced_sampler.py
generate_buffer
Creates index list of data instances, which is already balanced.
Exact result can be always different even when shuffle=False when non-zero element
in self.balance_state[key]["remainer"] exists.
Source code in SaigeToolkit/data/batch_sampler/balanced_sampler.py
_update_dataset_num_patch
Updates n_patch attribute in dataset, when indices is updated. (due to changes in remainer items)
Parameters:
-
indices(Union[deque, List[int]]) –file indices for calculating data patch number
Returns:
-
int(int) –number of patches in files
Source code in SaigeToolkit/data/batch_sampler/balanced_sampler.py
ClassBalancedSampler
Bases: BatchSampler
Sampler implementation for simple class balancing.
Uses class_index value in dataset file dictionaries.
When more than one classes exist in single image, the multiplier of
the rarest class within image will be applied to the data.
Raises:
-
IndexError–Will be raised when class index exceeds MAX_NUM_CLS.
Notes
- TODO: Weighted balancing.
- TODO: Cropper applicability.
Source code in SaigeToolkit/data/batch_sampler/class_sampler.py
build_batch_sampler
build_batch_sampler(_target_: str, **config) -> BatchSampler