mcy98 commited on
Commit
b76474c
·
verified ·
1 Parent(s): f7c98b4

Delete folder annotations/annotation_127 with huggingface_hub

Browse files
Files changed (30) hide show
  1. annotations/annotation_127/ICLR24_InfoBatch.pdf +0 -3
  2. annotations/annotation_127/InfoBatch/.gitignore +0 -219
  3. annotations/annotation_127/InfoBatch/.gitmodules +0 -12
  4. annotations/annotation_127/InfoBatch/README.md +0 -97
  5. annotations/annotation_127/InfoBatch/examples/cifar_example.py +0 -291
  6. annotations/annotation_127/InfoBatch/examples/lamb.py +0 -125
  7. annotations/annotation_127/InfoBatch/examples/lars.py +0 -172
  8. annotations/annotation_127/InfoBatch/examples/model.py +0 -142
  9. annotations/annotation_127/InfoBatch/figs/motivation.png +0 -3
  10. annotations/annotation_127/InfoBatch/figs/pipeline.png +0 -3
  11. annotations/annotation_127/InfoBatch/figs/three_line.png +0 -3
  12. annotations/annotation_127/InfoBatch/infobatch/__init__.py +0 -1
  13. annotations/annotation_127/InfoBatch/infobatch/infobatch.py +0 -423
  14. annotations/annotation_127/InfoBatch/research/README.md +0 -12
  15. annotations/annotation_127/InfoBatch/research/cifar_example.py +0 -193
  16. annotations/annotation_127/InfoBatch/research/infobatch.py +0 -104
  17. annotations/annotation_127/InfoBatch/research/lamb.py +0 -125
  18. annotations/annotation_127/InfoBatch/research/lars.py +0 -172
  19. annotations/annotation_127/InfoBatch/research/model.py +0 -142
  20. annotations/annotation_127/InfoBatch/setup.py +0 -33
  21. annotations/annotation_127/_runner_stderr.txt +0 -2
  22. annotations/annotation_127/_runner_stdout.txt +0 -13
  23. annotations/annotation_127/canonical.py +0 -422
  24. annotations/annotation_127/function_info.json +0 -672
  25. annotations/annotation_127/instruction.txt +0 -284
  26. annotations/annotation_127/latex.txt +0 -85
  27. annotations/annotation_127/pytest_report/report.xml +0 -1
  28. annotations/annotation_127/requirements.txt +0 -30
  29. annotations/annotation_127/test.py +0 -161
  30. annotations/annotation_127/test.sh +0 -23
annotations/annotation_127/ICLR24_InfoBatch.pdf DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:b9f6140b13cd2f8e03c69a1285da93f38c62a57e355c67c75cf84bd58db90a32
3
- size 3034129
 
 
 
 
annotations/annotation_127/InfoBatch/.gitignore DELETED
@@ -1,219 +0,0 @@
1
- # Sphinx
2
- docs/build
3
- docs/source/generated
4
-
5
- # Created by https://www.toptal.com/developers/gitignore/api/python
6
- # Edit at https://www.toptal.com/developers/gitignore?templates=python
7
-
8
- ### Python ###
9
- # Byte-compiled / optimized / DLL files
10
- __pycache__/
11
- *.py[cod]
12
- *$py.class
13
-
14
- # C extensions
15
- *.so
16
-
17
- # Distribution / packaging
18
- .Python
19
- build/
20
- develop-eggs/
21
- dist/
22
- downloads/
23
- eggs/
24
- .eggs/
25
- lib/
26
- lib64/
27
- parts/
28
- sdist/
29
- var/
30
- wheels/
31
- share/python-wheels/
32
- *.egg-info/
33
- .installed.cfg
34
- *.egg
35
- MANIFEST
36
-
37
- # PyInstaller
38
- # Usually these files are written by a python script from a template
39
- # before PyInstaller builds the exe, so as to inject date/other infos into it.
40
- *.manifest
41
- *.spec
42
-
43
- # Installer logs
44
- pip-log.txt
45
- pip-delete-this-directory.txt
46
-
47
- # Unit test / coverage reports
48
- htmlcov/
49
- .tox/
50
- .nox/
51
- .coverage
52
- .coverage.*
53
- .cache
54
- nosetests.xml
55
- coverage.xml
56
- *.cover
57
- *.py,cover
58
- .hypothesis/
59
- .pytest_cache/
60
- cover/
61
-
62
- # Translations
63
- *.mo
64
- *.pot
65
-
66
- # Django stuff:
67
- *.log
68
- local_settings.py
69
- db.sqlite3
70
- db.sqlite3-journal
71
-
72
- # Flask stuff:
73
- instance/
74
- .webassets-cache
75
-
76
- # Scrapy stuff:
77
- .scrapy
78
-
79
- # Sphinx documentation
80
- docs/_build/
81
-
82
- # PyBuilder
83
- .pybuilder/
84
- target/
85
-
86
- # Jupyter Notebook
87
- .ipynb_checkpoints
88
-
89
- # IPython
90
- profile_default/
91
- ipython_config.py
92
-
93
- # pyenv
94
- # For a library or package, you might want to ignore these files since the code is
95
- # intended to run in multiple environments; otherwise, check them in:
96
- # .python-version
97
-
98
- # pipenv
99
- # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
100
- # However, in case of collaboration, if having platform-specific dependencies or dependencies
101
- # having no cross-platform support, pipenv may install dependencies that don't work, or not
102
- # install all needed dependencies.
103
- #Pipfile.lock
104
-
105
- # poetry
106
- # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
107
- # This is especially recommended for binary packages to ensure reproducibility, and is more
108
- # commonly ignored for libraries.
109
- # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
110
- #poetry.lock
111
-
112
- # pdm
113
- # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
114
- #pdm.lock
115
- # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
116
- # in version control.
117
- # https://pdm.fming.dev/#use-with-ide
118
- .pdm.toml
119
-
120
- # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
- __pypackages__/
122
-
123
- # Celery stuff
124
- celerybeat-schedule
125
- celerybeat.pid
126
-
127
- # SageMath parsed files
128
- *.sage.py
129
-
130
- # Environments
131
- .env
132
- .venv
133
- env/
134
- venv/
135
- ENV/
136
- env.bak/
137
- venv.bak/
138
-
139
- # Spyder project settings
140
- .spyderproject
141
- .spyproject
142
-
143
- # Rope project settings
144
- .ropeproject
145
-
146
- # mkdocs documentation
147
- /site
148
-
149
- # mypy
150
- .mypy_cache/
151
- .dmypy.json
152
- dmypy.json
153
-
154
- # Pyre type checker
155
- .pyre/
156
-
157
- # pytype static type analyzer
158
- .pytype/
159
-
160
- # Cython debug symbols
161
- cython_debug/
162
-
163
- # PyCharm
164
- # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
- # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
- # and can be added to the global gitignore or merged into this file. For a more nuclear
167
- # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
- #.idea/
169
-
170
- ### Python Patch ###
171
- # Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
172
- poetry.toml
173
-
174
- # ruff
175
- .ruff_cache/
176
-
177
- # LSP config files
178
- pyrightconfig.json
179
-
180
- # End of https://www.toptal.com/developers/gitignore/api/python
181
-
182
- # Created by https://www.toptal.com/developers/gitignore/api/macos
183
- # Edit at https://www.toptal.com/developers/gitignore?templates=macos
184
-
185
- ### macOS ###
186
- # General
187
- .DS_Store
188
- .AppleDouble
189
- .LSOverride
190
-
191
- # Icon must end with two \r
192
- Icon
193
-
194
-
195
- # Thumbnails
196
- ._*
197
-
198
- # Files that might appear in the root of a volume
199
- .DocumentRevisions-V100
200
- .fseventsd
201
- .Spotlight-V100
202
- .TemporaryItems
203
- .Trashes
204
- .VolumeIcon.icns
205
- .com.apple.timemachine.donotpresent
206
-
207
- # Directories potentially created on remote AFP share
208
- .AppleDB
209
- .AppleDesktop
210
- Network Trash Folder
211
- Temporary Items
212
- .apdisk
213
-
214
- ### macOS Patch ###
215
- # iCloud generated files
216
- *.icloud
217
-
218
- # End of https://www.toptal.com/developers/gitignore/api/macos
219
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/InfoBatch/.gitmodules DELETED
@@ -1,12 +0,0 @@
1
- [submodule "examples/alpaca-lora"]
2
- path = examples/alpaca-lora
3
- url = https://github.com/henryqin1997/alpaca-lora
4
- [submodule "examples/mmsegmentation"]
5
- path = examples/mmsegmentation
6
- url = https://github.com/henryqin1997/mmsegmentation.git
7
- [submodule "examples/InfoBatch-ImageNet"]
8
- path = examples/InfoBatch-ImageNet
9
- url = https://github.com/henryqin1997/InfoBatch-ImageNet.git
10
- [submodule "examples/latent-diffusion-infobatch"]
11
- path = examples/latent-diffusion-infobatch
12
- url = https://github.com/henryqin1997/latent-diffusion-infobatch.git
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/InfoBatch/README.md DELETED
@@ -1,97 +0,0 @@
1
- <h2 align="center">InfoBatch</h2>
2
- <p align="center"><b>ICLR 2024 Oral</b> | <a href="https://arxiv.org/pdf/2303.04947.pdf">[Paper]</a> | <a href="https://github.com/NUS-HPC-AI-LAB/InfoBatch">[Code]</a> </p>
3
-
4
- InfoBatch is a tool for lossless deep learning training acceleration. It achieves lossless training speed-up by unbiased dynamic data pruning.
5
-
6
- ![image](https://github.com/NUS-HPC-AI-LAB/InfoBatch/blob/master/figs/pipeline.png)
7
-
8
- ## News
9
- [2024/9/24] 🔥 Ultralytics-InfoBatch in testing at https://github.com/henryqin1997/ultralytics-infobatch! Latent diffusion was added to examples!
10
-
11
- [2024/1/17] 🔥 New version with only 3 lines of change comes! Note that one should use a per-sample loss (to update the score and calculate batch loss)
12
-
13
- [2024/1/16] 🔥 Our work got accepted to ICLR 2024 (oral)! A new version with only 3 lines of change will be updated soon. Experiments included in the paper (and beyond) will be gradually updated with detail.
14
-
15
- [2023/8/1] 🔥 InfoBatch can now losslessly save 40.9% on CIFAR100 and ImageNet. We are updating paper content and preparing for public code.
16
-
17
- ## TODO List
18
-
19
- - [x] Plug-and-Play Implementation of InfoBatch
20
- - [ ] PyPI Registration
21
- - [x] Experiment: Classification on Cifar
22
- - [x] Experiment: Classification on ImageNet
23
- - [x] Experiment: Segmentation
24
- - [x] Experiment: Diffusion
25
- - [x] Experiment: Instruction Finetuning
26
- - [ ] Experiment: Detection (YOLOv8) on COCO
27
- - [x] Paper: Updated on Openreview
28
-
29
- ## Contents
30
- - [Install](#install)
31
- - [Get Started](#get-started)
32
- - [Experiments](#experiments)
33
- - [Citation](#citation)
34
-
35
- ## Install
36
-
37
- Install InfoBatch via
38
-
39
- ```bash
40
- pip install git+https://github.com/NUS-HPC-AI-Lab/InfoBatch
41
- ```
42
-
43
- Or you can clone this repo and install it locally.
44
-
45
- ```bash
46
- git clone https://github.com/NUS-HPC-AI-Lab/InfoBatch
47
- cd InfoBatch
48
- pip install -e .
49
- ```
50
-
51
- ## Get Started
52
- To adapt your code with InfoBatch, just download and import InfoBatch, and change the following three lines:
53
-
54
- ![image](https://github.com/NUS-HPC-AI-Lab/InfoBatch/blob/master/figs/three_line.png)
55
-
56
- Note that one should use a **per-sample loss** to update the score and calculate batch loss; if the **learning rate scheduler**
57
- is **step-based**, **adjust its steps-per-epoch accordingly** at beginning of each epoch.
58
-
59
- For research studies and more flexible codes, you can refer to the code in `research`.
60
-
61
- ## Experiments
62
-
63
- ### Cifar
64
-
65
- To run the CIFAR-100 example with baseline, run with delta=0:
66
- ```bash
67
- python3 examples/cifar_example.py \
68
- --model r50 --optimizer lars --max-lr 5.2 --delta 0.0
69
- ```
70
-
71
- To run the CIFAR-100 example with InfoBatch, run the following:
72
- ```bash
73
- python3 examples/cifar_example.py \
74
- --model r50 --optimizer lars --max-lr 5.2 --delta 0.875 --ratio 0.5 --use_info_batch
75
- ```
76
-
77
- Our example also supports mixed precision training and distributed data parallelism with the following command:
78
- ```bash
79
- CUDA_VISIBLE_DEVICES=0,1 python3 -m torch.distributed.launch --use_env --nnodes=1 --nproc_per_node=2 \
80
- --master_addr=127.0.0.1 --master_port=23456 --node_rank=0 cifar_example.py \
81
- --use_ddp --use_info_batch --fp16 \
82
- --model r50 --optimizer lars --max-lr 5.2 --delta 0.875 --ratio 0.5
83
- ```
84
-
85
- You may observe a performance drop when using the Distributed Data-Parallel (DDP) training approach compared to the Data Parallel (DP) approach on multiple GPUs, especially in versions prior to Pytorch 1.11. However, this is not specific to our algorithm itself.
86
-
87
- ## Citation
88
- ```bibtex
89
- @inproceedings{
90
- qin2024infobatch,
91
- title={InfoBatch: Lossless Training Speed Up by Unbiased Dynamic Data Pruning},
92
- author={Qin, Ziheng and Wang, Kai and Zheng, Zangwei and Gu, Jianyang and Peng, Xiangyu and Zhaopan Xu and Zhou, Daquan and Lei Shang and Baigui Sun and Xuansong Xie and You, Yang},
93
- booktitle={The Twelfth International Conference on Learning Representations},
94
- year={2024},
95
- url={https://openreview.net/forum?id=C61sk5LsK6}
96
- }
97
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/InfoBatch/examples/cifar_example.py DELETED
@@ -1,291 +0,0 @@
1
- import argparse
2
- import datetime
3
- import json
4
- import os
5
- import torch
6
- import torch.nn as nn
7
- import torchvision
8
- import torch.optim as optim
9
- import time
10
- from torch.utils.data import DataLoader
11
- from torch.utils.data.distributed import DistributedSampler
12
- from infobatch import InfoBatch
13
- from torchvision import transforms
14
- from model import *
15
- import torch.distributed as dist
16
-
17
- RANK = int(os.getenv('RANK', -1))
18
- LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1))
19
-
20
-
21
- def safe_print(*args, **kwargs):
22
- if RANK in (-1, 0):
23
- print(*args)
24
-
25
- def setup_ddp():
26
- world_size = int(os.getenv('WORLD_SIZE', 1))
27
- torch.cuda.set_device(LOCAL_RANK)
28
- dist.init_process_group('nccl', rank=RANK, world_size=world_size)
29
-
30
- def destroy_ddp():
31
- dist.destroy_process_group()
32
-
33
-
34
- if __name__ == '__main__':
35
- parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')
36
- parser.add_argument('--lr', default=0.2, type=float, help='learning rate')
37
- parser.add_argument('--resume', '-r', action='store_true',
38
- help='resume from checkpoint')
39
- parser.add_argument('--use_info_batch', action='store_true',
40
- help='whether use info batch or not.')
41
- parser.add_argument('--use_ddp', action='store_true', help='whether use ddp or not.')
42
- parser.add_argument('--fp16', action='store_true', help='use mix precision training')
43
- parser.add_argument('--batch-size', type=int, default=128, metavar='N',
44
- help='input batch size for training (default: 128)')
45
- parser.add_argument('--test-batch-size', type=int, default=512, metavar='N',
46
- help='input batch size for testing (default: 128)')
47
- parser.add_argument('--momentum', type=float, default=0.9, metavar='M',
48
- help='SGD momentum (default: 0.9)')
49
- parser.add_argument('--weight-decay', type=float, default=5e-4, metavar='W',
50
- help='SGD weight decay (default: 5e-4)')
51
- parser.add_argument('--optimizer', type=str, default='sgd',
52
- help='different optimizers')
53
- parser.add_argument('--label-smoothing', type=float, default=0.1)
54
- # onecycle scheduling arguments
55
- parser.add_argument('--max-lr', default=0.05, type=float)
56
- parser.add_argument('--div-factor', default=25, type=float)
57
- parser.add_argument('--final-div', default=10000, type=float)
58
- parser.add_argument('--num_epoch', default=200,
59
- type=int, help='training epochs')
60
- parser.add_argument('--pct-start', default=0.3, type=float)
61
- parser.add_argument('--shuffle', default=True, action='store_true')
62
- parser.add_argument('--ratio', default=0.5, type=float, help='prune ratio')
63
- parser.add_argument('--delta', default=0.875, type=float)
64
- parser.add_argument('--model', default='r18', type=str)
65
- args = parser.parse_args()
66
-
67
- if not torch.cuda.is_available():
68
- device = 'cpu'
69
- elif args.use_ddp:
70
- device = 'cuda:%d' % LOCAL_RANK
71
- setup_ddp()
72
- else:
73
- device = 'cuda:0'
74
- safe_print('==> Building model..')
75
-
76
- if args.model.lower() == 'r18':
77
- net = ResNet18(100)
78
- elif args.model.lower() == 'r50':
79
- net = ResNet50(num_classes=100)
80
- elif args.model.lower() == 'r101':
81
- net = ResNet101(num_classes=100)
82
- else:
83
- net = ResNet50(num_classes=100)
84
- net = net.to(device)
85
- if args.use_ddp:
86
- safe_print('use ddp')
87
- net = torch.nn.parallel.DistributedDataParallel(net, [LOCAL_RANK], LOCAL_RANK)
88
- else:
89
- safe_print('use normal data parallel')
90
- net = torch.nn.DataParallel(net)
91
- try:
92
- criterion = nn.CrossEntropyLoss(
93
- label_smoothing=args.label_smoothing, reduction='none').to(device)
94
- except:
95
- safe_print('warning! This version has no label smooth.')
96
- criterion = nn.CrossEntropyLoss(reduction='none').to(device)
97
- test_criterion = nn.CrossEntropyLoss().to(device)
98
-
99
- best_acc = 0 # best test accuracy
100
- best_loss = 1e3 # best test loss
101
- best_epoch = 0
102
- start_epoch = 0 # start from epoch 0 or last checkpoint epoch
103
-
104
-
105
- stats = ((0.5074, 0.4867, 0.4411), (0.2011, 0.1987, 0.2025))
106
- train_transform = transforms.Compose([
107
- transforms.RandomHorizontalFlip(),
108
- transforms.RandomCrop(32, padding=4, padding_mode="reflect"),
109
- transforms.ToTensor(),
110
- transforms.Normalize(*stats)
111
- ])
112
-
113
- test_transform = transforms.Compose([
114
- transforms.ToTensor(),
115
- transforms.Normalize(*stats)
116
- ])
117
-
118
- trainset = torchvision.datasets.CIFAR100(root='./cifar100', train=True, transform=train_transform,
119
- download=True)
120
-
121
- # 1.Substitute dataset with InfoBatch dataset, optionally set r; delta and num_epoch are needed to anneal with full data
122
- if args.use_info_batch:
123
- safe_print('Use info batch.')
124
- trainset = InfoBatch(trainset, args.num_epoch, args.ratio, args.delta)
125
- else:
126
- safe_print('Use normal full batch.')
127
-
128
- # 2.Substitute sampler
129
- sampler = None
130
- train_shuffle = True
131
- if args.use_info_batch:
132
- sampler = trainset.sampler
133
- train_shuffle = False
134
- if args.use_ddp and not args.use_info_batch:
135
- sampler = DistributedSampler(trainset, shuffle=True)
136
- train_shuffle = False
137
- safe_print(type(sampler))
138
- trainloader = DataLoader(trainset, batch_size=args.batch_size, shuffle=train_shuffle, num_workers=0, sampler=sampler)
139
-
140
- testset = torchvision.datasets.CIFAR100(
141
- root='./cifar100', train=False, download=True, transform=test_transform)
142
-
143
- testloader = DataLoader(testset, batch_size=100, shuffle=False, num_workers=4)
144
-
145
-
146
- # Model
147
-
148
-
149
- if args.optimizer.lower() == 'sgd':
150
- optimizer = optim.SGD(net.parameters(), lr=args.lr,
151
- momentum=args.momentum, weight_decay=args.weight_decay)
152
- elif args.optimizer.lower() == 'adam':
153
- optimizer = torch.optim.Adam(net.parameters(), lr=args.lr, momentum=args.momentum,
154
- weight_decay=args.weight_decay)
155
- elif args.optimizer.lower() == 'lars': # no tensorboardX
156
- from lars import Lars
157
- optimizer = Lars(net.parameters(), lr=args.lr,
158
- momentum=args.momentum, weight_decay=args.weight_decay)
159
- elif args.optimizer.lower() == 'lamb':
160
- from lamb import Lamb
161
- optimizer = Lamb(net.parameters(), lr=args.lr,
162
- momentum=args.momentum, weight_decay=args.weight_decay)
163
-
164
- lr_scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, args.max_lr, steps_per_epoch=len(trainloader),
165
- epochs=args.num_epoch, div_factor=args.div_factor,
166
- final_div_factor=args.final_div, pct_start=args.pct_start)
167
-
168
- train_acc = []
169
- valid_acc = []
170
- scaler = torch.cuda.amp.GradScaler(enabled=args.fp16)
171
-
172
- def train_info_batch(epoch):
173
- safe_print('\nEpoch: %d, iterations %d' % (epoch, len(trainloader)))
174
- net.train()
175
- train_loss = 0
176
- correct = 0
177
- total = 0
178
-
179
- for batch_idx, blobs in enumerate(trainloader):
180
- inputs, targets = blobs
181
- inputs, targets = inputs.to(device), targets.to(device)
182
- optimizer.zero_grad()
183
- with torch.cuda.amp.autocast(args.fp16):
184
- outputs = net(inputs)
185
- loss = criterion(outputs, targets)
186
- # 3. use <InfoBatch>.update(loss), all scoring/rescaling/getting mean is now conducted at the backend, see previous (research version) code for details.
187
- loss = trainset.update(loss)
188
- scaler.scale(loss).backward()
189
- scaler.step(optimizer)
190
- scaler.update()
191
- lr_scheduler.step()
192
- train_loss += loss.item()
193
- _, predicted = outputs.max(1)
194
- total += targets.size(0)
195
- correct += predicted.eq(targets).sum().item()
196
- safe_print('epoch:', epoch, ' Training Accuracy:', round(100. * correct /
197
- total, 3), ' Train loss:', round(train_loss / len(trainloader), 4))
198
- train_acc.append(correct / total)
199
-
200
-
201
- def train_normal(epoch):
202
- safe_print('\nEpoch: %d, iterations %d' % (epoch, len(trainloader)))
203
- net.train()
204
- train_loss = 0
205
- correct = 0
206
- total = 0
207
-
208
- for batch_idx, (inputs, targets) in enumerate(trainloader):
209
- inputs, targets = inputs.to(device), targets.to(device)
210
- optimizer.zero_grad()
211
- with torch.cuda.amp.autocast(args.fp16):
212
- outputs = net(inputs)
213
- loss = torch.mean(criterion(outputs, targets))
214
- scaler.scale(loss).backward()
215
- scaler.step(optimizer)
216
- scaler.update()
217
- lr_scheduler.step()
218
- train_loss += loss.item()
219
- _, predicted = outputs.max(1)
220
- total += targets.size(0)
221
- correct += predicted.eq(targets).sum().item()
222
- safe_print('epoch:', epoch, ' Training Accuracy:', round(100. * correct /
223
- total, 3), ' Train loss:', round(train_loss / len(trainloader), 4))
224
- train_acc.append(correct / total)
225
-
226
-
227
- def test(epoch):
228
- net.eval()
229
- test_loss = 0
230
- correct = 0
231
- total = 0
232
- global best_acc
233
- global best_loss
234
- global best_epoch
235
- with torch.no_grad():
236
- for batch_idx, (inputs, targets) in enumerate(testloader):
237
- inputs, targets = inputs.to(device), targets.to(device)
238
- outputs = net(inputs)
239
- loss = test_criterion(outputs, targets)
240
-
241
- test_loss += loss.item()
242
- _, predicted = outputs.max(1)
243
- total += targets.size(0)
244
- correct += predicted.eq(targets).sum().item()
245
- cur_acc = round(100. * correct / total, 3)
246
- cur_loss = round(test_loss / len(testloader), 4)
247
- safe_print('epoch: %d' % epoch, ' Test Acc: %.3f' % cur_acc,
248
- ' Test loss: %.4f' % cur_loss, ' Best info epoch %d, acc %.3f, loss %.4f' % (best_epoch, best_acc, best_loss))
249
- if cur_acc > best_acc:
250
- best_acc = cur_acc
251
- best_epoch = epoch
252
- if cur_loss < best_loss:
253
- best_loss = cur_loss
254
- valid_acc.append(cur_acc)
255
-
256
-
257
- total_time = 0
258
-
259
- for epoch in range(args.num_epoch):
260
- if args.use_ddp:
261
- trainloader.sampler.set_epoch(epoch)
262
- # 4. For epoch-based implementation, update the corresponding learning rate schedule according to steps of this epoch
263
- lr_scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, args.max_lr,
264
- steps_per_epoch=len(trainloader),
265
- epochs=args.num_epoch, div_factor=args.div_factor,
266
- final_div_factor=args.final_div, pct_start=args.pct_start,
267
- last_epoch=epoch * len(trainloader) - 1)
268
- end = time.time()
269
- train_info_batch(epoch) if args.use_info_batch else train_normal(epoch)
270
- total_time += time.time() - end
271
- test(epoch)
272
-
273
- if args.use_info_batch:
274
- safe_print('Total saved sample forwarding: ', trainset.get_pruned_count())
275
- safe_print('Total training time: ', total_time)
276
- pref = 'full_batch' if not args.use_info_batch else 'info_batch'
277
- fn = '{}{}-{}-epoch{}-batchsize{}-pct{}-labelsm{}-{}_cifar100_{}_log.json'.format(
278
- args.model,
279
- str(args.max_lr/args.div_factor),
280
- str(args.max_lr),
281
- args.num_epoch,
282
- args.batch_size,
283
- args.pct_start,
284
- args.label_smoothing,
285
- datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'), pref)
286
- if LOCAL_RANK in (-1, 0):
287
- file = open(fn, 'w+')
288
- json.dump([total_time, trainset.get_pruned_count() if args.use_info_batch else 0,
289
- args.ratio, train_acc, valid_acc], file)
290
- if args.use_ddp:
291
- destroy_ddp()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/InfoBatch/examples/lamb.py DELETED
@@ -1,125 +0,0 @@
1
- """Lamb optimizer."""
2
-
3
- import collections
4
- import math
5
-
6
- import torch
7
- # from tensorboardX import SummaryWriter
8
- from torch.optim import Optimizer
9
-
10
-
11
- # def log_lamb_rs(optimizer: Optimizer, event_writer: SummaryWriter, token_count: int):
12
- # """Log a histogram of trust ratio scalars in across layers."""
13
- # results = collections.defaultdict(list)
14
- # for group in optimizer.param_groups:
15
- # for p in group['params']:
16
- # state = optimizer.state[p]
17
- # for i in ('weight_norm', 'adam_norm', 'trust_ratio'):
18
- # if i in state:
19
- # results[i].append(state[i])
20
- #
21
- # for k, v in results.items():
22
- # event_writer.add_histogram(f'lamb/{k}', torch.tensor(v), token_count)
23
-
24
- class Lamb(Optimizer):
25
- r"""Implements Lamb algorithm.
26
-
27
- It has been proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_.
28
-
29
- Arguments:
30
- params (iterable): iterable of parameters to optimize or dicts defining
31
- parameter groups
32
- lr (float, optional): learning rate (default: 1e-3)
33
- betas (Tuple[float, float], optional): coefficients used for computing
34
- running averages of gradient and its square (default: (0.9, 0.999))
35
- eps (float, optional): term added to the denominator to improve
36
- numerical stability (default: 1e-8)
37
- weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
38
- adam (bool, optional): always use trust ratio = 1, which turns this into
39
- Adam. Useful for comparison purposes.
40
-
41
- .. _Large Batch Optimization for Deep Learning: Training BERT in 76 minutes:
42
- https://arxiv.org/abs/1904.00962
43
- """
44
-
45
- def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-6,
46
- weight_decay=0, adam=False):
47
- if not 0.0 <= lr:
48
- raise ValueError("Invalid learning rate: {}".format(lr))
49
- if not 0.0 <= eps:
50
- raise ValueError("Invalid epsilon value: {}".format(eps))
51
- if not 0.0 <= betas[0] < 1.0:
52
- raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0]))
53
- if not 0.0 <= betas[1] < 1.0:
54
- raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1]))
55
- defaults = dict(lr=lr, betas=betas, eps=eps,
56
- weight_decay=weight_decay)
57
- self.adam = adam
58
- super(Lamb, self).__init__(params, defaults)
59
-
60
- def step(self, closure=None):
61
- """Performs a single optimization step.
62
-
63
- Arguments:
64
- closure (callable, optional): A closure that reevaluates the model
65
- and returns the loss.
66
- """
67
- loss = None
68
- if closure is not None:
69
- loss = closure()
70
-
71
- for group in self.param_groups:
72
- for p in group['params']:
73
- if p.grad is None:
74
- continue
75
- grad = p.grad.data
76
- if grad.is_sparse:
77
- raise RuntimeError('Lamb does not support sparse gradients, consider SparseAdam instad.')
78
-
79
- state = self.state[p]
80
-
81
- # State initialization
82
- if len(state) == 0:
83
- state['step'] = 0
84
- # Exponential moving average of gradient values
85
- state['exp_avg'] = torch.zeros_like(p.data)
86
- # Exponential moving average of squared gradient values
87
- state['exp_avg_sq'] = torch.zeros_like(p.data)
88
-
89
- exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']
90
- beta1, beta2 = group['betas']
91
-
92
- state['step'] += 1
93
-
94
- # Decay the first and second moment running average coefficient
95
- # m_t
96
- exp_avg.mul_(beta1).add_(1 - beta1, grad)
97
- # v_t
98
- exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)
99
-
100
- # Paper v3 does not use debiasing.
101
- # bias_correction1 = 1 - beta1 ** state['step']
102
- # bias_correction2 = 1 - beta2 ** state['step']
103
- # Apply bias to lr to avoid broadcast.
104
- step_size = group['lr'] # * math.sqrt(bias_correction2) / bias_correction1
105
-
106
- weight_norm = p.data.pow(2).sum().sqrt().clamp(0, 10)
107
-
108
- adam_step = exp_avg / exp_avg_sq.sqrt().add(group['eps'])
109
- if group['weight_decay'] != 0:
110
- adam_step.add_(group['weight_decay'], p.data)
111
-
112
- adam_norm = adam_step.pow(2).sum().sqrt()
113
- if weight_norm == 0 or adam_norm == 0:
114
- trust_ratio = 1
115
- else:
116
- trust_ratio = weight_norm / adam_norm
117
- state['weight_norm'] = weight_norm
118
- state['adam_norm'] = adam_norm
119
- state['trust_ratio'] = trust_ratio
120
- if self.adam:
121
- trust_ratio = 1
122
-
123
- p.data.add_(-step_size * trust_ratio, adam_step)
124
-
125
- return loss
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/InfoBatch/examples/lars.py DELETED
@@ -1,172 +0,0 @@
1
- import torch
2
- from torch.optim.optimizer import Optimizer
3
- from typing import Dict, Iterable, Optional, Callable, Tuple
4
- from torch import nn
5
-
6
- """
7
- We recommend using create_optimizer_lars and setting bn_bias_separately=True
8
- instead of using class Lars directly, which helps LARS skip parameters
9
- in BatchNormalization and bias, and has better performance in general.
10
- Polynomial Warmup learning rate decay is also helpful for better performance in general.
11
- """
12
-
13
-
14
- def create_optimizer_lars(model, lr, momentum, weight_decay, bn_bias_separately, epsilon):
15
- if bn_bias_separately:
16
- optimizer = Lars([
17
- dict(params=get_common_parameters(model, exclude_func=get_norm_bias_parameters)),
18
- dict(params=get_norm_bias_parameters(model), weight_decay=0, lars=False)],
19
- lr=lr,
20
- momentum=momentum,
21
- weight_decay=weight_decay,
22
- epsilon=epsilon)
23
- else:
24
- optimizer = Lars(model.parameters(),
25
- lr=lr,
26
- momentum=momentum,
27
- weight_decay=weight_decay,
28
- epsilon=epsilon)
29
- return optimizer
30
-
31
-
32
- class Lars(Optimizer):
33
- r"""Implements the LARS optimizer from `"Large batch training of convolutional networks"
34
- <https://arxiv.org/pdf/1708.03888.pdf>`_.
35
- Args:
36
- params (iterable): iterable of parameters to optimize or dicts defining
37
- parameter groups
38
- lr (float, optional): learning rate
39
- momentum (float, optional): momentum factor (default: 0)
40
- eeta (float, optional): LARS coefficient as used in the paper (default: 1e-3)
41
- weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
42
- """
43
-
44
- def __init__(
45
- self,
46
- params: Iterable[torch.nn.Parameter],
47
- lr=1e-3,
48
- momentum=0,
49
- eeta=1e-3,
50
- weight_decay=0,
51
- epsilon=0.0
52
- ) -> None:
53
- if not isinstance(lr, float) or lr < 0.0:
54
- raise ValueError("Invalid learning rate: {}".format(lr))
55
- if momentum < 0.0:
56
- raise ValueError("Invalid momentum value: {}".format(momentum))
57
- if weight_decay < 0.0:
58
- raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
59
- if eeta <= 0:
60
- raise ValueError("Invalid eeta value: {}".format(eeta))
61
- if epsilon < 0:
62
- raise ValueError("Invalid epsilon value: {}".format(epsilon))
63
- defaults = dict(lr=lr, momentum=momentum,
64
- weight_decay=weight_decay, eeta=eeta, epsilon=epsilon, lars=True)
65
-
66
- super().__init__(params, defaults)
67
-
68
- def set_decay(self,weight_decay):
69
- for group in self.param_groups:
70
- group['weight_decay'] = weight_decay
71
-
72
- @torch.no_grad()
73
- def step(self, closure=None):
74
- """Performs a single optimization step.
75
- Arguments:
76
- closure (callable, optional): A closure that reevaluates the model
77
- and returns the loss.
78
- """
79
- loss = None
80
- if closure is not None:
81
- with torch.enable_grad():
82
- loss = closure()
83
-
84
- for group in self.param_groups:
85
- weight_decay = group['weight_decay']
86
- momentum = group['momentum']
87
- eeta = group['eeta']
88
- lr = group['lr']
89
- lars = group['lars']
90
- eps = group['epsilon']
91
-
92
- for p in group['params']:
93
- if p.grad is None:
94
- continue
95
- decayed_grad = p.grad
96
- scaled_lr = lr
97
- if lars:
98
- w_norm = torch.norm(p)
99
- g_norm = torch.norm(p.grad)
100
- trust_ratio = torch.where(
101
- w_norm > 0 and g_norm > 0,
102
- eeta * w_norm / (g_norm + weight_decay * w_norm + eps),
103
- torch.ones_like(w_norm)
104
- )
105
- trust_ratio.clamp_(0.0, 50)
106
- scaled_lr *= trust_ratio.item()
107
- if weight_decay != 0:
108
- decayed_grad = decayed_grad.add(p, alpha=weight_decay)
109
- decayed_grad = torch.clamp(decayed_grad, -10.0, 10.0)
110
-
111
- if momentum != 0:
112
- param_state = self.state[p]
113
- if 'momentum_buffer' not in param_state:
114
- buf = param_state['momentum_buffer'] = torch.clone(
115
- decayed_grad).detach()
116
- else:
117
- buf = param_state['momentum_buffer']
118
- buf.mul_(momentum).add_(decayed_grad)
119
- decayed_grad = buf
120
-
121
- p.add_(decayed_grad, alpha=-scaled_lr)
122
-
123
- return loss
124
-
125
-
126
- """
127
- Functions which help to skip bias and BatchNorm
128
- """
129
- BN_CLS = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d)
130
-
131
-
132
- def get_parameters_from_cls(module, cls_):
133
- def get_members_fn(m):
134
- if isinstance(m, cls_):
135
- return m._parameters.items()
136
- else:
137
- return dict()
138
-
139
- named_parameters = module._named_members(get_members_fn=get_members_fn)
140
- for name, param in named_parameters:
141
- yield param
142
-
143
-
144
- def get_norm_parameters(module):
145
- return get_parameters_from_cls(module, (nn.LayerNorm, *BN_CLS))
146
-
147
-
148
- def get_bias_parameters(module, exclude_func=None):
149
- excluded_parameters = set()
150
- if exclude_func is not None:
151
- for param in exclude_func(module):
152
- excluded_parameters.add(param)
153
- for name, param in module.named_parameters():
154
- if param not in excluded_parameters and 'bias' in name:
155
- yield param
156
-
157
-
158
- def get_norm_bias_parameters(module):
159
- for param in get_norm_parameters(module):
160
- yield param
161
- for param in get_bias_parameters(module, exclude_func=get_norm_parameters):
162
- yield param
163
-
164
-
165
- def get_common_parameters(module, exclude_func=None):
166
- excluded_parameters = set()
167
- if exclude_func is not None:
168
- for param in exclude_func(module):
169
- excluded_parameters.add(param)
170
- for name, param in module.named_parameters():
171
- if param not in excluded_parameters:
172
- yield param
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/InfoBatch/examples/model.py DELETED
@@ -1,142 +0,0 @@
1
- '''ResNet in PyTorch.
2
- For Pre-activation ResNet, see 'preact_resnet.py'.
3
- Reference:
4
- [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
5
- Deep Residual Learning for Image Recognition. arXiv:1512.03385
6
- '''
7
- import torch
8
- import torch.nn as nn
9
- import torch.nn.functional as F
10
-
11
-
12
- class BasicBlock(nn.Module):
13
- expansion = 1
14
-
15
- def __init__(self, in_planes, planes, stride=1):
16
- super(BasicBlock, self).__init__()
17
- self.conv1 = nn.Conv2d(
18
- in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
19
- self.bn1 = nn.BatchNorm2d(planes)
20
- self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
21
- stride=1, padding=1, bias=False)
22
- self.bn2 = nn.BatchNorm2d(planes)
23
-
24
- self.shortcut = nn.Sequential()
25
- if stride != 1 or in_planes != self.expansion*planes:
26
- self.shortcut = nn.Sequential(
27
- nn.Conv2d(in_planes, self.expansion*planes,
28
- kernel_size=1, stride=stride, bias=False),
29
- nn.BatchNorm2d(self.expansion*planes)
30
- )
31
-
32
- def forward(self, x):
33
- out = F.relu(self.bn1(self.conv1(x)))
34
- out = self.bn2(self.conv2(out))
35
- out += self.shortcut(x)
36
- out = F.relu(out)
37
- return out
38
-
39
-
40
- class Bottleneck(nn.Module):
41
- expansion = 4
42
-
43
- def __init__(self, in_planes, planes, stride=1):
44
- super(Bottleneck, self).__init__()
45
- self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)
46
- self.bn1 = nn.BatchNorm2d(planes)
47
- self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
48
- stride=stride, padding=1, bias=False)
49
- self.bn2 = nn.BatchNorm2d(planes)
50
- self.conv3 = nn.Conv2d(planes, self.expansion *
51
- planes, kernel_size=1, bias=False)
52
- self.bn3 = nn.BatchNorm2d(self.expansion*planes)
53
-
54
- self.shortcut = nn.Sequential()
55
- if stride != 1 or in_planes != self.expansion*planes:
56
- self.shortcut = nn.Sequential(
57
- nn.Conv2d(in_planes, self.expansion*planes,
58
- kernel_size=1, stride=stride, bias=False),
59
- nn.BatchNorm2d(self.expansion*planes)
60
- )
61
-
62
- def forward(self, x):
63
- out = F.relu(self.bn1(self.conv1(x)))
64
- out = F.relu(self.bn2(self.conv2(out)))
65
- out = self.bn3(self.conv3(out))
66
- out += self.shortcut(x)
67
- out = F.relu(out)
68
- return out
69
-
70
-
71
- class ResNet(nn.Module):
72
- def __init__(self, block, num_blocks, num_classes=10):
73
- super(ResNet, self).__init__()
74
- self.in_planes = 64
75
-
76
- self.conv1 = nn.Conv2d(3, 64, kernel_size=3,
77
- stride=1, padding=1, bias=False)
78
- self.bn1 = nn.BatchNorm2d(64)
79
- self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)
80
- self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)
81
- self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)
82
- self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)
83
- self.avgpool = nn.AdaptiveAvgPool2d((1,1))
84
- self.linear = nn.Linear(512*block.expansion, num_classes)
85
-
86
- def _make_layer(self, block, planes, num_blocks, stride):
87
- strides = [stride] + [1]*(num_blocks-1)
88
- layers = []
89
- for stride in strides:
90
- layers.append(block(self.in_planes, planes, stride))
91
- self.in_planes = planes * block.expansion
92
- return nn.Sequential(*layers)
93
-
94
- def forward(self, x):
95
- out = F.relu(self.bn1(self.conv1(x)))
96
- out = self.layer1(out)
97
- out = self.layer2(out)
98
- out = self.layer3(out)
99
- out = self.layer4(out)
100
- # out = F.avg_pool2d(out, 4)
101
- out = self.avgpool(out)
102
- out = out.view(out.size(0), -1)
103
- out = self.linear(out)
104
- return out
105
-
106
- def create_emb(self,x):
107
- out = F.relu(self.bn1(self.conv1(x)))
108
- out = self.layer1(out)
109
- out = self.layer2(out)
110
- out = self.layer3(out)
111
- out = self.layer4(out)
112
- # out = F.avg_pool2d(out, 4)
113
- out = self.avgpool(out)
114
- out = out.view(out.size(0), -1)
115
- return out
116
-
117
- def ResNet18(num_classes=10):
118
- return ResNet(BasicBlock, [2, 2, 2, 2], num_classes=num_classes)
119
-
120
-
121
- def ResNet34():
122
- return ResNet(BasicBlock, [3, 4, 6, 3])
123
-
124
-
125
- def ResNet50(num_classes=10):
126
- return ResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes)
127
-
128
-
129
- def ResNet101(num_classes=10):
130
- return ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes)
131
-
132
-
133
- def ResNet152():
134
- return ResNet(Bottleneck, [3, 8, 36, 3])
135
-
136
-
137
- def test():
138
- net = ResNet18()
139
- y = net(torch.randn(1, 3, 32, 32))
140
- print(y.size())
141
-
142
- # test()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/InfoBatch/figs/motivation.png DELETED

Git LFS Details

  • SHA256: fe3dca303ca2cd4ca432ab465be2dc25c4a2ee9b80d3434665427debf67bcfad
  • Pointer size: 131 Bytes
  • Size of remote file: 588 kB
annotations/annotation_127/InfoBatch/figs/pipeline.png DELETED

Git LFS Details

  • SHA256: fa7c4418167db2448bd130f5c6684b379815d2a6bfb0fe117532c294b211d71d
  • Pointer size: 131 Bytes
  • Size of remote file: 430 kB
annotations/annotation_127/InfoBatch/figs/three_line.png DELETED

Git LFS Details

  • SHA256: 82c00339876f0761d46010c9b7ad2ae39e8d710d68868c0039da2c86a722c3ea
  • Pointer size: 131 Bytes
  • Size of remote file: 125 kB
annotations/annotation_127/InfoBatch/infobatch/__init__.py DELETED
@@ -1 +0,0 @@
1
- from .infobatch import InfoBatch
 
 
annotations/annotation_127/InfoBatch/infobatch/infobatch.py DELETED
@@ -1,423 +0,0 @@
1
- # === Appended from canonical.py ===
2
- import math
3
- import numpy as np
4
- from typing import Iterator, Optional
5
- import torch
6
- from torch.utils.data.dataloader import _BaseDataLoaderIter
7
- from torch.utils.data import Dataset, _DatasetKind
8
- from torch.utils.data.distributed import DistributedSampler
9
- from operator import itemgetter
10
- import torch.distributed as dist
11
- import warnings
12
-
13
- __all__ = ['InfoBatch']
14
-
15
-
16
- def info_hack_indices(self):
17
- """
18
- This function is a "monkey patch" that replaces the default `__next__` method of PyTorch's internal `_BaseDataLoaderIter`.
19
- Its primary purpose is to intercept the batch of data *before* it is returned by the DataLoader's iterator.
20
-
21
- Paper Correspondence:
22
- - The paper describes updating scores H_t(z) for samples z within the current batch S_t (Section 2.3, Eq. 4) and
23
- rescaling their gradients (Section 2.3). To do this, the implementation needs to know which sample indices
24
- correspond to the data in the current batch.
25
- - Standard PyTorch DataLoaders do not expose the indices of the batch directly when iterating. This function
26
- "hacks" the iterator to solve this problem.
27
-
28
- Implementation Details (Not in Paper):
29
- - It calls the original `_next_data()` method to fetch the batch.
30
- - Crucially, if the dataset is an `InfoBatch` instance, `_next_data()` is expected to return a tuple of `(indices, data)`.
31
- This is achieved by modifying `InfoBatch.__getitem__`.
32
- - It then calls `self._dataset.set_active_indices(indices)` to inform the `InfoBatch` dataset wrapper about the
33
- indices of the samples currently being processed. This information is stored and later used in the `InfoBatch.update()`
34
- method to correctly associate losses with samples.
35
- - The function then returns only the `data` part of the batch, maintaining the expected behavior for the user's training loop.
36
- - The `_reset()` call with `type: ignore[call-arg]` is a workaround for a potential bug or type-hinting issue in PyTorch,
37
- as discussed in PyTorch issue #76750, where `_reset()` was found to be called without a required argument.
38
- """
39
- with torch.autograd.profiler.record_function(self._profile_name):
40
- if self._sampler_iter is None:
41
- # This internal method is called to reset the sampler iterator, e.g., at the beginning of an epoch.
42
- # The type: ignore comment suggests a known issue or mismatch with type hints in the PyTorch source.
43
- # See PyTorch GitHub issue #76750 for context.
44
- self._reset() # type: ignore[call-arg]
45
- if isinstance(self._dataset, InfoBatch):
46
- # If the dataset is an InfoBatch instance, we expect __getitem__ to return both indices and data.
47
- indices, data = self._next_data()
48
- else:
49
- # For standard datasets, it just returns data.
50
- data = self._next_data()
51
- self._num_yielded += 1
52
- if self._dataset_kind == _DatasetKind.Iterable and \
53
- self._IterableDataset_len_called is not None and \
54
- self._num_yielded > self._IterableDataset_len_called:
55
- warn_msg = ("Length of IterableDataset {} was reported to be {} (when accessing len(dataloader)), but {} "
56
- "samples have been fetched. ").format(self._dataset, self._IterableDataset_len_called,
57
- self._num_yielded)
58
- if self._num_workers > 0:
59
- warn_msg += ("For multiprocessing data-loading, this could be caused by not properly configuring the "
60
- "IterableDataset replica at each worker. Please see "
61
- "https://pytorch.org/docs/stable/data.html#torch.utils.data.IterableDataset for examples.")
62
- warnings.warn(warn_msg)
63
- if isinstance(self._dataset, InfoBatch):
64
- # This is the key step of the hack: we store the indices of the current batch
65
- # in the InfoBatch dataset object for later use in the `update` method.
66
- self._dataset.set_active_indices(indices)
67
- return data
68
-
69
- # This line performs the monkey-patching, replacing the original __next__ method
70
- # of the DataLoader iterator with our custom `info_hack_indices` function.
71
- # This makes the entire mechanism work without requiring users to modify their training loop.
72
- _BaseDataLoaderIter.__next__ = info_hack_indices
73
-
74
-
75
- @torch.no_grad()
76
- def concat_all_gather(tensor, dim=0):
77
- """
78
- Performs `all_gather` operation on the provided tensors across all distributed processes.
79
- This is a utility function for distributed training.
80
-
81
- Paper Correspondence:
82
- - The paper doesn't explicitly detail the distributed training implementation. However, to ensure that the
83
- sample scores `H_t(z)` are consistent across all workers, the loss values from the global batch (across all GPUs)
84
- must be collected. This function achieves that.
85
-
86
- Implementation Details (Not in Paper):
87
- - It gathers tensors from all processes in the distributed group and concatenates them.
88
- - This is used in `InfoBatch.update()` to gather the `(indices, loss_values)` pairs from all workers,
89
- so that the master `scores` tensor can be updated correctly with information from the entire global batch.
90
- """
91
- tensors_gather = [torch.ones_like(tensor)
92
- for _ in range(dist.get_world_size())]
93
- dist.all_gather(tensors_gather, tensor, async_op=False)
94
- output = torch.cat(tensors_gather, dim=dim)
95
- return output
96
-
97
-
98
- class InfoBatch(Dataset):
99
- """
100
- InfoBatch is a Dataset wrapper that implements the data pruning strategy described in the paper
101
- "INFOBATCH: LOSSLESS TRAINING SPEED UP BY UNBIASED DYNAMIC DATA PRUNING" (https://arxiv.org/pdf/2303.04947.pdf).
102
- It dynamically prunes less informative samples during training to accelerate convergence without sacrificing accuracy.
103
-
104
- .. note::
105
- The wrapped dataset is assumed to be a map-style dataset of constant size.
106
-
107
- Args:
108
- dataset: The original map-style dataset to be wrapped.
109
- num_epochs (int): The total number of training epochs. Used to schedule the annealing phase.
110
- prune_ratio (float, optional): The probability `r` of pruning a sample identified as "well-learned".
111
- Corresponds to `r` in Eq. 3 of the paper. Defaults to 0.5.
112
- delta (float, optional): The fraction of total epochs during which pruning is active. After `delta * num_epochs`,
113
- pruning stops (annealing phase). Corresponds to `δ` in Eq. 10. Defaults to 0.875.
114
- """
115
-
116
- def __init__(self, dataset: Dataset, num_epochs: int,
117
- prune_ratio: float = 0.5, delta: float = 0.875):
118
- self.dataset = dataset
119
- # `keep_ratio` corresponds to (1 - r) in the paper's formulation. It's the proportion of
120
- # well-learned samples that are kept, not pruned.
121
- self.keep_ratio = min(1.0, max(1e-1, 1.0 - prune_ratio))
122
- self.num_epochs = num_epochs
123
- # `delta` corresponds to the annealing hyperparameter δ from Section 2.4.
124
- self.delta = delta
125
-
126
- # `self.scores` stores the loss value H_t(z) for each sample z.
127
- # Paper Discrepancy: The paper (Section 2.3) mentions initializing scores to {1}.
128
- # Here, they are initialized to 3. This is a practical choice to set a high initial loss,
129
- # ensuring that no samples are considered "well-learned" and pruned before the first
130
- # forward pass and score update have occurred.
131
- self.scores = torch.ones(len(self.dataset)) * 3
132
-
133
- # `self.weights` stores the rescaling factor γ_t(z) for each sample. It is initialized to 1.
134
- self.weights = torch.ones(len(self.dataset))
135
- self.num_pruned_samples = 0
136
- # `self.cur_batch_index` is a temporary holder for the indices of the current batch,
137
- # populated by the `info_hack_indices` monkey patch.
138
- self.cur_batch_index = None
139
-
140
- def __getattr__(self, name):
141
- # This is a standard wrapper pattern. If an attribute is not found on InfoBatch,
142
- # it tries to retrieve it from the wrapped `self.dataset`. This makes InfoBatch
143
- # transparent for methods/attributes of the original dataset.
144
- return getattr(self.dataset, name)
145
-
146
- def set_active_indices(self, cur_batch_indices: torch.Tensor):
147
- """Stores the indices of the samples in the current batch."""
148
- self.cur_batch_index = cur_batch_indices
149
-
150
- def update(self, values):
151
- """
152
- Updates the scores of the samples in the last batch and returns the rescaled loss.
153
- This method should be called in the training loop with the loss tensor of the current batch.
154
-
155
- Paper Correspondence:
156
- - Score Update: Implements Eq. 4: H_{t+1}(z) = L(z) for samples z in the current batch S_t.
157
- - Expectation Rescaling: Implements the core idea from Section 2.3. It multiplies the incoming
158
- loss `values` by the stored `weights` (γ_t(z)), effectively rescaling the gradients during backpropagation.
159
- The objective becomes E_{z in S_t}[γ_t(z)L(z, θ)], as in Eq. 6.
160
- """
161
- assert isinstance(values, torch.Tensor)
162
- batch_size = values.shape[0]
163
- assert len(self.cur_batch_index) == batch_size, 'The number of provided indices does not match the batch size.'
164
- device = values.device
165
- weights = self.weights[self.cur_batch_index].to(device)
166
- indices = self.cur_batch_index.to(device)
167
- loss_val = values.detach().clone()
168
- # Clear the indices after use.
169
- self.cur_batch_index = []
170
-
171
- # Handle distributed training by gathering losses and indices from all workers.
172
- if dist.is_available() and dist.is_initialized():
173
- # Concatenate indices and losses for efficient gathering.
174
- iv = torch.cat([indices.view(1, -1), loss_val.view(1, -1)], dim=0)
175
- # Gather from all processes.
176
- iv_whole_group = concat_all_gather(iv, 1)
177
- indices = iv_whole_group[0]
178
- loss_val = iv_whole_group[1]
179
-
180
- # Update the scores for the samples in the global batch.
181
- self.scores[indices.cpu().long()] = loss_val.cpu()
182
-
183
- # Apply expectation rescaling: multiply the loss by the per-sample weight.
184
- # When backpropagation occurs, this will scale the gradients accordingly.
185
- values.mul_(weights)
186
-
187
- # Return the mean of the rescaled loss for the batch.
188
- return values.mean()
189
-
190
- def __len__(self):
191
- """Returns the size of the original, unpruned dataset."""
192
- return len(self.dataset)
193
-
194
- def __getitem__(self, index):
195
- """
196
- Overrides `__getitem__` to return both the data and its index.
197
-
198
- Implementation Details (Not in Paper):
199
- - This modification is essential for the `info_hack_indices` monkey patch to work.
200
- - The DataLoader's collate function will receive a list of `(index, data_tuple)` pairs.
201
- - The default collate function can handle this, creating a batch of indices and a batch of data.
202
- - Our monkey patch then intercepts this pair, passes the indices to the InfoBatch object,
203
- and returns only the data batch to the user.
204
- """
205
- return index, self.dataset[index]
206
-
207
- def prune(self):
208
- """
209
- Implements the soft pruning and weight rescaling logic for one epoch.
210
-
211
- Paper Correspondence:
212
- - This method directly implements the soft pruning policy from Eq. 3: P_t(z) = r if H_t(z) < H̄_t, and 0 otherwise.
213
- - It also sets the weights for expectation rescaling as described in Section 2.3.
214
- """
215
- # 1. Identify well-learned samples: H_t(z) < H̄_t (mean of all scores).
216
- well_learned_mask = (self.scores < self.scores.mean()).numpy()
217
- well_learned_indices = np.where(well_learned_mask)[0]
218
- remained_indices = np.where(~well_learned_mask)[0].tolist()
219
-
220
- # 2. Soft Pruning: Randomly select a `keep_ratio` (1-r) fraction of well-learned samples to keep for training.
221
- selected_indices = np.random.choice(well_learned_indices, int(
222
- self.keep_ratio * len(well_learned_indices)), replace=False)
223
-
224
- # 3. Expectation Rescaling: Reset all weights to 1, then scale up the weights of the kept "well-learned" samples.
225
- self.reset_weights()
226
- if len(selected_indices) > 0:
227
- # The weight γ_t(z) is set to 1 / (1 - r) for these samples.
228
- self.weights[selected_indices] = 1 / self.keep_ratio
229
- remained_indices.extend(selected_indices)
230
-
231
- self.num_pruned_samples += len(self.dataset) - len(remained_indices)
232
- np.random.shuffle(remained_indices)
233
-
234
- # Return the final list of indices to be used for training in the upcoming epoch.
235
- return remained_indices
236
-
237
- @property
238
- def sampler(self):
239
- """Provides a compatible sampler for the DataLoader."""
240
- sampler = IBSampler(self)
241
- if dist.is_available() and dist.is_initialized():
242
- # If in a distributed environment, wrap the sampler for data parallelism.
243
- sampler = DistributedIBSampler(sampler)
244
- return sampler
245
-
246
- def no_prune(self):
247
- """
248
- Returns a shuffled list of all sample indices. Used during the annealing phase
249
- when pruning is turned off.
250
- """
251
- samples_indices = list(range(len(self)))
252
- np.random.shuffle(samples_indices)
253
- return samples_indices
254
-
255
- def mean_score(self):
256
- """Returns the mean of all current sample scores."""
257
- return self.scores.mean()
258
-
259
- def get_weights(self, indexes):
260
- """Returns the rescaling weights for a given set of indices."""
261
- return self.weights[indexes]
262
-
263
- def get_pruned_count(self):
264
- """Returns the total number of samples pruned so far."""
265
- return self.num_pruned_samples
266
-
267
- @property
268
- def stop_prune(self):
269
- """
270
- Calculates the epoch number at which to stop pruning, based on the annealing schedule.
271
- Corresponds to δ * C from Section 2.4.
272
- """
273
- return self.num_epochs * self.delta
274
-
275
- def reset_weights(self):
276
- """Resets all sample weights to 1."""
277
- self.weights[:] = 1
278
-
279
-
280
- class IBSampler(object):
281
- """
282
- InfoBatch Sampler (IBSampler).
283
- This is a custom sampler that generates the list of indices for each epoch.
284
- It orchestrates the pruning and annealing schedule.
285
-
286
- Implementation Details (Not in Paper):
287
- - This class acts as a PyTorch sampler by implementing `__iter__` and `__len__`.
288
- - It is stateful, tracking the number of `iterations` (epochs).
289
- """
290
- def __init__(self, dataset: InfoBatch):
291
- self.dataset = dataset
292
- self.stop_prune = dataset.stop_prune
293
- self.iterations = 0
294
- self.sample_indices = None
295
- self.iter_obj = None
296
- self.reset()
297
-
298
- def __getitem__(self, idx):
299
- return self.sample_indices[idx]
300
-
301
- def reset(self):
302
- """
303
- Resets the sampler's state at the beginning of each epoch.
304
- This is where the decision to prune or not is made.
305
-
306
- Paper Correspondence:
307
- - This method implements the annealing logic from Eq. 10.
308
- - If `self.iterations > self.stop_prune`, it calls `self.dataset.no_prune()`, switching to the full dataset.
309
- - Otherwise, it calls `self.dataset.prune()` to get a pruned set of indices.
310
- """
311
- np.random.seed(self.iterations) # For reproducibility of the shuffle.
312
- if self.iterations > self.stop_prune:
313
- # Annealing phase: stop pruning and use the full dataset.
314
- if self.iterations == self.stop_prune + 1:
315
- # On the first epoch of annealing, reset weights to 1.
316
- self.dataset.reset_weights()
317
- self.sample_indices = self.dataset.no_prune()
318
- else:
319
- # Pruning phase: get a new set of pruned indices for this epoch.
320
- self.sample_indices = self.dataset.prune()
321
- self.iter_obj = iter(self.sample_indices)
322
- self.iterations += 1
323
-
324
- def __next__(self):
325
- """Returns the next index from the iterator."""
326
- return next(self.iter_obj) # may raise StopIteration
327
-
328
- def __len__(self):
329
- """Returns the number of samples for the current epoch (which can change)."""
330
- return len(self.sample_indices)
331
-
332
- def __iter__(self):
333
- """
334
- Called by the DataLoader at the beginning of each epoch.
335
- Resets the state and returns itself as the iterator.
336
- """
337
- self.reset()
338
- return self
339
-
340
-
341
- class DistributedIBSampler(DistributedSampler):
342
- """
343
- A distributed wrapper for `IBSampler`.
344
- This ensures that when using multiple GPUs/processes, each process receives a unique,
345
- non-overlapping subset of the indices generated by `IBSampler`.
346
-
347
- Implementation Details (Not in Paper):
348
- - It inherits from PyTorch's `DistributedSampler` and adapts its logic.
349
- - It uses a nested `DatasetFromSampler` class to make the `IBSampler` compatible with the
350
- `DistributedSampler`'s expectation of a `Dataset` object. This is a common pattern for
351
- wrapping dynamic samplers in a distributed setting.
352
- - The `__iter__` method contains the core logic for splitting the epoch's indices among the ranks.
353
- """
354
- class DatasetFromSampler(Dataset):
355
- """A helper class to wrap a sampler to behave like a dataset."""
356
- def __init__(self, sampler: IBSampler):
357
- self.dataset = sampler
358
-
359
- def reset(self, ):
360
- self.dataset.reset()
361
-
362
- def __len__(self):
363
- return len(self.dataset)
364
-
365
- def __getitem__(self, index: int):
366
- """Gets an element from the sampler's current index list."""
367
- return self.dataset[index]
368
-
369
- def __init__(self, dataset: IBSampler, num_replicas: Optional[int] = None,
370
- rank: Optional[int] = None, shuffle: bool = True,
371
- seed: int = 0, drop_last: bool = True) -> None:
372
- # The 'dataset' here is actually our IBSampler, which we wrap.
373
- sampler = self.DatasetFromSampler(dataset)
374
- super(DistributedIBSampler, self).__init__(
375
- sampler, num_replicas, rank, shuffle, seed, drop_last)
376
- self.sampler = sampler
377
- self.dataset = sampler.dataset.dataset # The actual, original dataset.
378
- self.iter_obj = None
379
-
380
- def __iter__(self) -> Iterator[int]:
381
- """
382
- Generates the indices for the current process/rank for one epoch.
383
- """
384
- # 1. Reset the underlying IBSampler to generate the full list of indices for this epoch.
385
- self.sampler.reset()
386
-
387
- # 2. Standard DistributedSampler logic to calculate how many samples this rank should handle.
388
- if self.drop_last and len(self.sampler) % self.num_replicas != 0:
389
- self.num_samples = math.ceil(
390
- (len(self.sampler) - self.num_replicas) / self.num_replicas
391
- )
392
- else:
393
- self.num_samples = math.ceil(
394
- len(self.sampler) / self.num_replicas)
395
- self.total_size = self.num_samples * self.num_replicas
396
-
397
- # 3. Get the full list of indices from the underlying sampler.
398
- if self.shuffle:
399
- # Deterministically shuffle the full list of indices based on the epoch.
400
- g = torch.Generator()
401
- g.manual_seed(self.seed + self.epoch)
402
- indices = torch.randperm(len(self.sampler), generator=g).tolist()
403
- else:
404
- indices = list(range(len(self.sampler)))
405
-
406
- # 4. Pad or truncate the index list to be evenly divisible by the number of replicas.
407
- if not self.drop_last:
408
- padding_size = self.total_size - len(indices)
409
- if padding_size <= len(indices):
410
- indices += indices[:padding_size]
411
- else:
412
- indices += (indices * math.ceil(padding_size /
413
- len(indices)))[:padding_size]
414
- else:
415
- indices = indices[:self.total_size]
416
- assert len(indices) == self.total_size
417
-
418
- # 5. Select the subset of indices for the current rank.
419
- indices = indices[self.rank:self.total_size:self.num_replicas]
420
-
421
- # 6. Return an iterator over the original indices (from the sampler) that correspond to the shuffled, sliced indices.
422
- self.iter_obj = iter(itemgetter(*indices)(self.sampler))
423
- return self.iter_obj
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/InfoBatch/research/README.md DELETED
@@ -1,12 +0,0 @@
1
- ## Purpose of this directory
2
- Here we provide a code version for the research study. All steps are more straightforward.
3
-
4
- ## CIFAR Experiments
5
- To run the CIFAR-100 example with Baseline, execute in the command line:
6
- ```angular2html
7
- CUDA_VISIBLE_DEVICES=0 python3 cifar_example.py --model r50 --optimizer lars --max-lr 5.2 --delta 0.0
8
- ```
9
- To run the CIFAR-100 example with InfoBatch, execute in the command line:
10
- ```angular2html
11
- CUDA_VISIBLE_DEVICES=0 python3 cifar_example.py --model r50 --optimizer lars --max-lr 5.2 --ratio 0.5 --delta 0.875
12
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/InfoBatch/research/cifar_example.py DELETED
@@ -1,193 +0,0 @@
1
- import argparse
2
- import datetime
3
- import json
4
- import numpy as np
5
- import os
6
- import torch
7
- import torch.nn as nn
8
- import torchvision
9
- import torch.optim as optim
10
- import torch.backends.cudnn as cudnn
11
- import time
12
-
13
- from infobatch import InfoBatch
14
- from torch.utils.data import Dataset, DataLoader, WeightedRandomSampler
15
- from torchvision import transforms, utils
16
- from model import *
17
-
18
- parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')
19
- parser.add_argument('--lr', default=0.2, type=float, help='learning rate')
20
- parser.add_argument('--resume', '-r', action='store_true',
21
- help='resume from checkpoint')
22
- parser.add_argument('--batch-size', type=int, default=128, metavar='N',
23
- help='input batch size for training (default: 128)')
24
- parser.add_argument('--test-batch-size', type=int, default=128, metavar='N',
25
- help='input batch size for testing (default: 128)')
26
- parser.add_argument('--momentum', type=float, default=0.9, metavar='M',
27
- help='SGD momentum (default: 0.9)')
28
- parser.add_argument('--weight-decay', type=float, default=5e-4, metavar='W',
29
- help='SGD weight decay (default: 5e-4)')
30
- parser.add_argument('--optimizer',type=str,default='lars',
31
- help='different optimizers')
32
- parser.add_argument('--label-smoothing',type=float,default=0.1)
33
- # onecycle scheduling arguments
34
- parser.add_argument('--max-lr',default=0.1,type=float)
35
- parser.add_argument('--div-factor',default=25,type=float)
36
- parser.add_argument('--final-div',default=10000,type=float)
37
- parser.add_argument('--num-epoch',default=200,type=int)
38
- parser.add_argument('--pct-start',default=0.3,type=float)
39
- parser.add_argument('--shuffle', default=False, action='store_true')
40
- parser.add_argument('--ratio',default=0.5,type=float)
41
- parser.add_argument('--delta',default=0.875,type=float)
42
- parser.add_argument('--model',default='r50',type=str)
43
- args = parser.parse_args()
44
-
45
- device = 'cuda' if torch.cuda.is_available() else 'cpu'
46
- best_acc = 0 # best test accuracy
47
- start_epoch = 0 # start from epoch 0 or last checkpoint epoch
48
-
49
-
50
- stats = ((0.5074,0.4867,0.4411),(0.2011,0.1987,0.2025))
51
- train_transform = transforms.Compose([
52
- transforms.RandomHorizontalFlip(),
53
- transforms.RandomCrop(32,padding=4,padding_mode="reflect"),
54
- transforms.ToTensor(),
55
- transforms.Normalize(*stats)
56
- ])
57
-
58
- test_transform = transforms.Compose([
59
- transforms.ToTensor(),
60
- transforms.Normalize(*stats)
61
- ])
62
-
63
- trainset = torchvision.datasets.CIFAR100(root='/tmp/cifar100', train=True, transform=train_transform,
64
- download=True)
65
-
66
- #1.Substitute dataset with InfoBatch dataset, optionally set r; delta and num_epoch are needed to anneal with full data
67
- trainset = InfoBatch(trainset, args.ratio if args.ratio else None, args.num_epoch, args.delta)
68
-
69
- #2.Substitute sampler
70
- trainloader = torch.utils.data.DataLoader(
71
- trainset, batch_size=args.batch_size, shuffle=args.shuffle, sampler = trainset.pruning_sampler())
72
-
73
- testset = torchvision.datasets.CIFAR100(
74
- root='/tmp/cifar100', train=False, download=True, transform=test_transform)
75
-
76
- testloader = torch.utils.data.DataLoader(
77
- testset, batch_size=100, shuffle=False)
78
-
79
-
80
- # Model
81
- print('==> Building model..')
82
-
83
- if args.model.lower()=='r18':
84
- net = ResNet18(100)
85
- elif args.model.lower()=='r50':
86
- net = ResNet50(num_classes=100)
87
- elif args.model.lower()=='r101':
88
- net = ResNet101(num_classes=100)
89
- else:
90
- net = ResNet50(num_classes=100)
91
-
92
- net = net.to(device)
93
- criterion = nn.CrossEntropyLoss(label_smoothing=args.label_smoothing, reduction='none')
94
- test_criterion = nn.CrossEntropyLoss()
95
-
96
- if args.optimizer.lower()=='sgd':
97
- optimizer = optim.SGD(net.parameters(), lr=args.lr,momentum=args.momentum,weight_decay=args.weight_decay)
98
- elif args.optimizer.lower()=='adam':
99
- optimizer = torch.optim.Adam(net.parameters(), lr=args.lr,
100
- weight_decay=args.weight_decay)
101
- elif args.optimizer.lower() == 'lars':#no tensorboardX
102
- from lars import Lars
103
- optimizer = Lars(net.parameters(), lr=args.lr,momentum=args.momentum,weight_decay=args.weight_decay)
104
- elif args.optimizer.lower() == 'lamb':
105
- from lamb import Lamb
106
- optimizer = Lamb(net.parameters(),lr=args.lr,momentum=args.momentum,weight_decay=args.weight_decay)
107
-
108
- lr_scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer,args.max_lr,steps_per_epoch=len(trainloader),
109
- epochs=args.num_epoch,div_factor=args.div_factor,
110
- final_div_factor=args.final_div,pct_start=args.pct_start)
111
-
112
- train_acc = []
113
- valid_acc = []
114
-
115
- # Training
116
- def train(epoch):
117
- print('\nEpoch: %d' % epoch)
118
- net.train()
119
- train_loss = 0
120
- correct = 0
121
- total = 0
122
-
123
- #3.Change loading content from loader
124
- for batch_idx, (inputs, targets, indices, rescale_weight) in enumerate(trainloader):
125
- #4.Put corresponding tensor onto device, and send back the scores
126
- inputs, targets, rescale_weight = inputs.to(device), targets.to(device), rescale_weight.to(device)
127
- optimizer.zero_grad()
128
- outputs = net(inputs)
129
- loss = criterion(outputs, targets)
130
- trainset.__setscore__(indices.detach().cpu().numpy(),loss.detach().cpu().numpy())
131
- loss = loss*rescale_weight
132
- loss = torch.mean(loss)
133
- #-----------Only need to adapt above code in training------------#
134
- loss.backward()
135
- optimizer.step()
136
- lr_scheduler.step()
137
- train_loss += loss.item()
138
- _, predicted = outputs.max(1)
139
- total += targets.size(0)
140
- correct += predicted.eq(targets).sum().item()
141
-
142
- print('epoch:', epoch, ' Training Accuracy:', 100. * correct / total, ' Train loss:', train_loss / len(trainloader))
143
- train_acc.append(correct/total)
144
-
145
- def test(epoch):
146
- net.eval()
147
- test_loss = 0
148
- correct = 0
149
- total = 0
150
- with torch.no_grad():
151
- for batch_idx, (inputs, targets) in enumerate(testloader):
152
- inputs, targets = inputs.to(device), targets.to(device)
153
- outputs = net(inputs)
154
- loss = test_criterion(outputs, targets)
155
-
156
- test_loss += loss.item()
157
- _, predicted = outputs.max(1)
158
- total += targets.size(0)
159
- correct += predicted.eq(targets).sum().item()
160
-
161
- print('epoch:', epoch, ' Test Accuracy:', 100. * correct / total, ' Test loss:', test_loss/len(testloader))
162
- valid_acc.append(correct/total)
163
-
164
- total_time = 0
165
-
166
- for epoch in range(args.num_epoch):
167
- # 5. For epoch based implementation, update corresponding learning rate schedule according to steps this epoch
168
- lr_scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, args.max_lr,
169
- steps_per_epoch=len(trainloader),
170
- epochs=args.num_epoch, div_factor=args.div_factor,
171
- final_div_factor=args.final_div, pct_start=args.pct_start,
172
- last_epoch=epoch * len(trainloader) - 1)
173
- end = time.time()
174
- train(epoch)
175
- total_time+=time.time()-end
176
- test(epoch)
177
-
178
-
179
- print('Total saved sample forwarding: ', trainset.total_save())
180
- print('Total training time: ', total_time)
181
-
182
- fn = '{}{}-{}-epoch{}-batchsize{}-pct{}-labelsm{}-{}_cifar100_InfoBatch_log.json'.format(
183
- args.model,
184
- str(args.max_lr/args.div_factor),
185
- str(args.max_lr),
186
- args.num_epoch,
187
- args.batch_size,
188
- args.pct_start,
189
- args.label_smoothing,
190
- datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
191
-
192
- file = open(fn,'w+')
193
- json.dump([total_time,trainset.total_save(),args.ratio,train_acc,valid_acc],file)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/InfoBatch/research/infobatch.py DELETED
@@ -1,104 +0,0 @@
1
- import math
2
- import numpy as np
3
- from torch.utils.data import Dataset
4
-
5
- class InfoBatch(Dataset):
6
- def __init__(self, dataset, ratio = 0.5, num_epoch=None, delta = 0.875):
7
- self.dataset = dataset
8
- self.ratio = ratio
9
- self.num_epoch = num_epoch
10
- self.delta = delta
11
- self.scores = np.ones([len(self.dataset)])
12
- self.transform = dataset.transform
13
- self.weights = np.ones(len(self.dataset))
14
- self.save_num = 0
15
-
16
- def __setscore__(self, indices, values):
17
- self.scores[indices] = values
18
-
19
- def __len__(self):
20
- return len(self.dataset)
21
-
22
- def __getitem__(self, index):
23
- data, target = self.dataset[index]
24
- weight = self.weights[index]
25
- return data, target, index, weight
26
-
27
- def prune(self):
28
- # prune samples that are well learned, rebalence the weight by scaling up remaining
29
- # well learned samples' learning rate to keep estimation about the same
30
- # for the next version, also consider new class balance
31
-
32
- b = self.scores<self.scores.mean()
33
- well_learned_samples = np.where(b)[0]
34
- pruned_samples = []
35
- pruned_samples.extend(np.where(np.invert(b))[0])
36
- selected = np.random.choice(well_learned_samples, int(self.ratio*len(well_learned_samples)),replace=False)
37
- self.reset_weights()
38
- if len(selected)>0:
39
- self.weights[selected]=1/self.ratio
40
- pruned_samples.extend(selected)
41
- print('Cut {} samples for next iteration'.format(len(self.dataset)-len(pruned_samples)))
42
- self.save_num += len(self.dataset)-len(pruned_samples)
43
- np.random.shuffle(pruned_samples)
44
- return pruned_samples
45
-
46
- def pruning_sampler(self):
47
- return InfoBatchSampler(self, self.num_epoch, self.delta)
48
-
49
- def no_prune(self):
50
- samples = list(range(len(self.dataset)))
51
- np.random.shuffle(samples)
52
- return samples
53
-
54
- def mean_score(self):
55
- return self.scores.mean()
56
-
57
- def normal_sampler_no_prune(self):
58
- return InfoBatchSampler(self.no_prune)
59
-
60
- def get_weights(self,indexes):
61
- return self.weights[indexes]
62
-
63
- def total_save(self):
64
- return self.save_num
65
-
66
- def reset_weights(self):
67
- self.weights = np.ones(len(self.dataset))
68
-
69
-
70
-
71
- class InfoBatchSampler():
72
- def __init__(self, infobatch_dataset, num_epoch = math.inf, delta = 1):
73
- self.infobatch_dataset = infobatch_dataset
74
- self.seq = None
75
- self.stop_prune = num_epoch * delta
76
- self.seed = 0
77
- self.reset()
78
-
79
- def reset(self):
80
- np.random.seed(self.seed)
81
- self.seed+=1
82
- if self.seed>self.stop_prune:
83
- if self.seed <= self.stop_prune+1:
84
- self.infobatch_dataset.reset_weights()
85
- self.seq = self.infobatch_dataset.no_prune()
86
- else:
87
- self.seq = self.infobatch_dataset.prune()
88
- self.ite = iter(self.seq)
89
- self.new_length = len(self.seq)
90
-
91
- def __next__(self):
92
- try:
93
- nxt = next(self.ite)
94
- return nxt
95
- except StopIteration:
96
- self.reset()
97
- raise StopIteration
98
-
99
- def __len__(self):
100
- return len(self.seq)
101
-
102
- def __iter__(self):
103
- self.ite = iter(self.seq)
104
- return self
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/InfoBatch/research/lamb.py DELETED
@@ -1,125 +0,0 @@
1
- """Lamb optimizer."""
2
-
3
- import collections
4
- import math
5
-
6
- import torch
7
- # from tensorboardX import SummaryWriter
8
- from torch.optim import Optimizer
9
-
10
-
11
- # def log_lamb_rs(optimizer: Optimizer, event_writer: SummaryWriter, token_count: int):
12
- # """Log a histogram of trust ratio scalars in across layers."""
13
- # results = collections.defaultdict(list)
14
- # for group in optimizer.param_groups:
15
- # for p in group['params']:
16
- # state = optimizer.state[p]
17
- # for i in ('weight_norm', 'adam_norm', 'trust_ratio'):
18
- # if i in state:
19
- # results[i].append(state[i])
20
- #
21
- # for k, v in results.items():
22
- # event_writer.add_histogram(f'lamb/{k}', torch.tensor(v), token_count)
23
-
24
- class Lamb(Optimizer):
25
- r"""Implements Lamb algorithm.
26
-
27
- It has been proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_.
28
-
29
- Arguments:
30
- params (iterable): iterable of parameters to optimize or dicts defining
31
- parameter groups
32
- lr (float, optional): learning rate (default: 1e-3)
33
- betas (Tuple[float, float], optional): coefficients used for computing
34
- running averages of gradient and its square (default: (0.9, 0.999))
35
- eps (float, optional): term added to the denominator to improve
36
- numerical stability (default: 1e-8)
37
- weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
38
- adam (bool, optional): always use trust ratio = 1, which turns this into
39
- Adam. Useful for comparison purposes.
40
-
41
- .. _Large Batch Optimization for Deep Learning: Training BERT in 76 minutes:
42
- https://arxiv.org/abs/1904.00962
43
- """
44
-
45
- def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-6,
46
- weight_decay=0, adam=False):
47
- if not 0.0 <= lr:
48
- raise ValueError("Invalid learning rate: {}".format(lr))
49
- if not 0.0 <= eps:
50
- raise ValueError("Invalid epsilon value: {}".format(eps))
51
- if not 0.0 <= betas[0] < 1.0:
52
- raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0]))
53
- if not 0.0 <= betas[1] < 1.0:
54
- raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1]))
55
- defaults = dict(lr=lr, betas=betas, eps=eps,
56
- weight_decay=weight_decay)
57
- self.adam = adam
58
- super(Lamb, self).__init__(params, defaults)
59
-
60
- def step(self, closure=None):
61
- """Performs a single optimization step.
62
-
63
- Arguments:
64
- closure (callable, optional): A closure that reevaluates the model
65
- and returns the loss.
66
- """
67
- loss = None
68
- if closure is not None:
69
- loss = closure()
70
-
71
- for group in self.param_groups:
72
- for p in group['params']:
73
- if p.grad is None:
74
- continue
75
- grad = p.grad.data
76
- if grad.is_sparse:
77
- raise RuntimeError('Lamb does not support sparse gradients, consider SparseAdam instad.')
78
-
79
- state = self.state[p]
80
-
81
- # State initialization
82
- if len(state) == 0:
83
- state['step'] = 0
84
- # Exponential moving average of gradient values
85
- state['exp_avg'] = torch.zeros_like(p.data)
86
- # Exponential moving average of squared gradient values
87
- state['exp_avg_sq'] = torch.zeros_like(p.data)
88
-
89
- exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']
90
- beta1, beta2 = group['betas']
91
-
92
- state['step'] += 1
93
-
94
- # Decay the first and second moment running average coefficient
95
- # m_t
96
- exp_avg.mul_(beta1).add_(1 - beta1, grad)
97
- # v_t
98
- exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)
99
-
100
- # Paper v3 does not use debiasing.
101
- # bias_correction1 = 1 - beta1 ** state['step']
102
- # bias_correction2 = 1 - beta2 ** state['step']
103
- # Apply bias to lr to avoid broadcast.
104
- step_size = group['lr'] # * math.sqrt(bias_correction2) / bias_correction1
105
-
106
- weight_norm = p.data.pow(2).sum().sqrt().clamp(0, 10)
107
-
108
- adam_step = exp_avg / exp_avg_sq.sqrt().add(group['eps'])
109
- if group['weight_decay'] != 0:
110
- adam_step.add_(group['weight_decay'], p.data)
111
-
112
- adam_norm = adam_step.pow(2).sum().sqrt()
113
- if weight_norm == 0 or adam_norm == 0:
114
- trust_ratio = 1
115
- else:
116
- trust_ratio = weight_norm / adam_norm
117
- state['weight_norm'] = weight_norm
118
- state['adam_norm'] = adam_norm
119
- state['trust_ratio'] = trust_ratio
120
- if self.adam:
121
- trust_ratio = 1
122
-
123
- p.data.add_(-step_size * trust_ratio, adam_step)
124
-
125
- return loss
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/InfoBatch/research/lars.py DELETED
@@ -1,172 +0,0 @@
1
- import torch
2
- from torch.optim.optimizer import Optimizer
3
- from typing import Dict, Iterable, Optional, Callable, Tuple
4
- from torch import nn
5
-
6
- """
7
- We recommend using create_optimizer_lars and setting bn_bias_separately=True
8
- instead of using class Lars directly, which helps LARS skip parameters
9
- in BatchNormalization and bias, and has better performance in general.
10
- Polynomial Warmup learning rate decay is also helpful for better performance in general.
11
- """
12
-
13
-
14
- def create_optimizer_lars(model, lr, momentum, weight_decay, bn_bias_separately, epsilon):
15
- if bn_bias_separately:
16
- optimizer = Lars([
17
- dict(params=get_common_parameters(model, exclude_func=get_norm_bias_parameters)),
18
- dict(params=get_norm_bias_parameters(model), weight_decay=0, lars=False)],
19
- lr=lr,
20
- momentum=momentum,
21
- weight_decay=weight_decay,
22
- epsilon=epsilon)
23
- else:
24
- optimizer = Lars(model.parameters(),
25
- lr=lr,
26
- momentum=momentum,
27
- weight_decay=weight_decay,
28
- epsilon=epsilon)
29
- return optimizer
30
-
31
-
32
- class Lars(Optimizer):
33
- r"""Implements the LARS optimizer from `"Large batch training of convolutional networks"
34
- <https://arxiv.org/pdf/1708.03888.pdf>`_.
35
- Args:
36
- params (iterable): iterable of parameters to optimize or dicts defining
37
- parameter groups
38
- lr (float, optional): learning rate
39
- momentum (float, optional): momentum factor (default: 0)
40
- eeta (float, optional): LARS coefficient as used in the paper (default: 1e-3)
41
- weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
42
- """
43
-
44
- def __init__(
45
- self,
46
- params: Iterable[torch.nn.Parameter],
47
- lr=1e-3,
48
- momentum=0,
49
- eeta=1e-3,
50
- weight_decay=0,
51
- epsilon=0.0
52
- ) -> None:
53
- if not isinstance(lr, float) or lr < 0.0:
54
- raise ValueError("Invalid learning rate: {}".format(lr))
55
- if momentum < 0.0:
56
- raise ValueError("Invalid momentum value: {}".format(momentum))
57
- if weight_decay < 0.0:
58
- raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
59
- if eeta <= 0:
60
- raise ValueError("Invalid eeta value: {}".format(eeta))
61
- if epsilon < 0:
62
- raise ValueError("Invalid epsilon value: {}".format(epsilon))
63
- defaults = dict(lr=lr, momentum=momentum,
64
- weight_decay=weight_decay, eeta=eeta, epsilon=epsilon, lars=True)
65
-
66
- super().__init__(params, defaults)
67
-
68
- def set_decay(self,weight_decay):
69
- for group in self.param_groups:
70
- group['weight_decay'] = weight_decay
71
-
72
- @torch.no_grad()
73
- def step(self, closure=None):
74
- """Performs a single optimization step.
75
- Arguments:
76
- closure (callable, optional): A closure that reevaluates the model
77
- and returns the loss.
78
- """
79
- loss = None
80
- if closure is not None:
81
- with torch.enable_grad():
82
- loss = closure()
83
-
84
- for group in self.param_groups:
85
- weight_decay = group['weight_decay']
86
- momentum = group['momentum']
87
- eeta = group['eeta']
88
- lr = group['lr']
89
- lars = group['lars']
90
- eps = group['epsilon']
91
-
92
- for p in group['params']:
93
- if p.grad is None:
94
- continue
95
- decayed_grad = p.grad
96
- scaled_lr = lr
97
- if lars:
98
- w_norm = torch.norm(p)
99
- g_norm = torch.norm(p.grad)
100
- trust_ratio = torch.where(
101
- w_norm > 0 and g_norm > 0,
102
- eeta * w_norm / (g_norm + weight_decay * w_norm + eps),
103
- torch.ones_like(w_norm)
104
- )
105
- trust_ratio.clamp_(0.0, 50)
106
- scaled_lr *= trust_ratio.item()
107
- if weight_decay != 0:
108
- decayed_grad = decayed_grad.add(p, alpha=weight_decay)
109
- decayed_grad = torch.clamp(decayed_grad, -10.0, 10.0)
110
-
111
- if momentum != 0:
112
- param_state = self.state[p]
113
- if 'momentum_buffer' not in param_state:
114
- buf = param_state['momentum_buffer'] = torch.clone(
115
- decayed_grad).detach()
116
- else:
117
- buf = param_state['momentum_buffer']
118
- buf.mul_(momentum).add_(decayed_grad)
119
- decayed_grad = buf
120
-
121
- p.add_(decayed_grad, alpha=-scaled_lr)
122
-
123
- return loss
124
-
125
-
126
- """
127
- Functions which help to skip bias and BatchNorm
128
- """
129
- BN_CLS = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d)
130
-
131
-
132
- def get_parameters_from_cls(module, cls_):
133
- def get_members_fn(m):
134
- if isinstance(m, cls_):
135
- return m._parameters.items()
136
- else:
137
- return dict()
138
-
139
- named_parameters = module._named_members(get_members_fn=get_members_fn)
140
- for name, param in named_parameters:
141
- yield param
142
-
143
-
144
- def get_norm_parameters(module):
145
- return get_parameters_from_cls(module, (nn.LayerNorm, *BN_CLS))
146
-
147
-
148
- def get_bias_parameters(module, exclude_func=None):
149
- excluded_parameters = set()
150
- if exclude_func is not None:
151
- for param in exclude_func(module):
152
- excluded_parameters.add(param)
153
- for name, param in module.named_parameters():
154
- if param not in excluded_parameters and 'bias' in name:
155
- yield param
156
-
157
-
158
- def get_norm_bias_parameters(module):
159
- for param in get_norm_parameters(module):
160
- yield param
161
- for param in get_bias_parameters(module, exclude_func=get_norm_parameters):
162
- yield param
163
-
164
-
165
- def get_common_parameters(module, exclude_func=None):
166
- excluded_parameters = set()
167
- if exclude_func is not None:
168
- for param in exclude_func(module):
169
- excluded_parameters.add(param)
170
- for name, param in module.named_parameters():
171
- if param not in excluded_parameters:
172
- yield param
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/InfoBatch/research/model.py DELETED
@@ -1,142 +0,0 @@
1
- '''ResNet in PyTorch.
2
- For Pre-activation ResNet, see 'preact_resnet.py'.
3
- Reference:
4
- [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
5
- Deep Residual Learning for Image Recognition. arXiv:1512.03385
6
- '''
7
- import torch
8
- import torch.nn as nn
9
- import torch.nn.functional as F
10
-
11
-
12
- class BasicBlock(nn.Module):
13
- expansion = 1
14
-
15
- def __init__(self, in_planes, planes, stride=1):
16
- super(BasicBlock, self).__init__()
17
- self.conv1 = nn.Conv2d(
18
- in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
19
- self.bn1 = nn.BatchNorm2d(planes)
20
- self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
21
- stride=1, padding=1, bias=False)
22
- self.bn2 = nn.BatchNorm2d(planes)
23
-
24
- self.shortcut = nn.Sequential()
25
- if stride != 1 or in_planes != self.expansion*planes:
26
- self.shortcut = nn.Sequential(
27
- nn.Conv2d(in_planes, self.expansion*planes,
28
- kernel_size=1, stride=stride, bias=False),
29
- nn.BatchNorm2d(self.expansion*planes)
30
- )
31
-
32
- def forward(self, x):
33
- out = F.relu(self.bn1(self.conv1(x)))
34
- out = self.bn2(self.conv2(out))
35
- out += self.shortcut(x)
36
- out = F.relu(out)
37
- return out
38
-
39
-
40
- class Bottleneck(nn.Module):
41
- expansion = 4
42
-
43
- def __init__(self, in_planes, planes, stride=1):
44
- super(Bottleneck, self).__init__()
45
- self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)
46
- self.bn1 = nn.BatchNorm2d(planes)
47
- self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
48
- stride=stride, padding=1, bias=False)
49
- self.bn2 = nn.BatchNorm2d(planes)
50
- self.conv3 = nn.Conv2d(planes, self.expansion *
51
- planes, kernel_size=1, bias=False)
52
- self.bn3 = nn.BatchNorm2d(self.expansion*planes)
53
-
54
- self.shortcut = nn.Sequential()
55
- if stride != 1 or in_planes != self.expansion*planes:
56
- self.shortcut = nn.Sequential(
57
- nn.Conv2d(in_planes, self.expansion*planes,
58
- kernel_size=1, stride=stride, bias=False),
59
- nn.BatchNorm2d(self.expansion*planes)
60
- )
61
-
62
- def forward(self, x):
63
- out = F.relu(self.bn1(self.conv1(x)))
64
- out = F.relu(self.bn2(self.conv2(out)))
65
- out = self.bn3(self.conv3(out))
66
- out += self.shortcut(x)
67
- out = F.relu(out)
68
- return out
69
-
70
-
71
- class ResNet(nn.Module):
72
- def __init__(self, block, num_blocks, num_classes=10):
73
- super(ResNet, self).__init__()
74
- self.in_planes = 64
75
-
76
- self.conv1 = nn.Conv2d(3, 64, kernel_size=3,
77
- stride=1, padding=1, bias=False)
78
- self.bn1 = nn.BatchNorm2d(64)
79
- self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)
80
- self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)
81
- self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)
82
- self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)
83
- self.avgpool = nn.AdaptiveAvgPool2d((1,1))
84
- self.linear = nn.Linear(512*block.expansion, num_classes)
85
-
86
- def _make_layer(self, block, planes, num_blocks, stride):
87
- strides = [stride] + [1]*(num_blocks-1)
88
- layers = []
89
- for stride in strides:
90
- layers.append(block(self.in_planes, planes, stride))
91
- self.in_planes = planes * block.expansion
92
- return nn.Sequential(*layers)
93
-
94
- def forward(self, x):
95
- out = F.relu(self.bn1(self.conv1(x)))
96
- out = self.layer1(out)
97
- out = self.layer2(out)
98
- out = self.layer3(out)
99
- out = self.layer4(out)
100
- # out = F.avg_pool2d(out, 4)
101
- out = self.avgpool(out)
102
- out = out.view(out.size(0), -1)
103
- out = self.linear(out)
104
- return out
105
-
106
- def create_emb(self,x):
107
- out = F.relu(self.bn1(self.conv1(x)))
108
- out = self.layer1(out)
109
- out = self.layer2(out)
110
- out = self.layer3(out)
111
- out = self.layer4(out)
112
- # out = F.avg_pool2d(out, 4)
113
- out = self.avgpool(out)
114
- out = out.view(out.size(0), -1)
115
- return out
116
-
117
- def ResNet18(num_classes=10):
118
- return ResNet(BasicBlock, [2, 2, 2, 2], num_classes=num_classes)
119
-
120
-
121
- def ResNet34():
122
- return ResNet(BasicBlock, [3, 4, 6, 3])
123
-
124
-
125
- def ResNet50(num_classes=10):
126
- return ResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes)
127
-
128
-
129
- def ResNet101(num_classes=10):
130
- return ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes)
131
-
132
-
133
- def ResNet152():
134
- return ResNet(Bottleneck, [3, 8, 36, 3])
135
-
136
-
137
- def test():
138
- net = ResNet18()
139
- y = net(torch.randn(1, 3, 32, 32))
140
- print(y.size())
141
-
142
- # test()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/InfoBatch/setup.py DELETED
@@ -1,33 +0,0 @@
1
- import setuptools
2
-
3
- with open("README.md", "r") as fh:
4
- long_description = fh.read()
5
-
6
- setuptools.setup(
7
- name="infobatch",
8
- license='MIT',
9
- version="0.1.0",
10
- author="Ziheng Qin",
11
- author_email="zihengq@comp.nus.edu.sg",
12
- description="InfoBatch code implementation",
13
- long_description=long_description,
14
- long_description_content_type="text/markdown",
15
- url="https://github.com/henryqin1997/InfoBatch",
16
- packages=setuptools.find_packages(),
17
- keywords=[
18
- 'artificial intelligence',
19
- 'deep learning',
20
- 'dataloader',
21
- 'acceleration'
22
- ],
23
- install_requires=[
24
- 'torch>=1.11'
25
- ],
26
- classifiers=[
27
- "Programming Language :: Python :: 3.6",
28
- "License :: OSI Approved :: MIT License",
29
- 'Intended Audience :: Developers',
30
- 'Topic :: Scientific/Engineering :: Artificial Intelligence',
31
- ],
32
- python_requires='>=3.6',
33
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/_runner_stderr.txt DELETED
@@ -1,2 +0,0 @@
1
- bash: cannot set terminal process group (728353): Inappropriate ioctl for device
2
- bash: no job control in this shell
 
 
 
annotations/annotation_127/_runner_stdout.txt DELETED
@@ -1,13 +0,0 @@
1
- ============================= test session starts ==============================
2
- platform linux -- Python 3.10.18, pytest-8.4.1, pluggy-1.6.0
3
- rootdir: /home/linus/code/research_code_gen/code_agent/work_dir/dataset/annotations/annotation_127/InfoBatch
4
- plugins: timeout-2.4.0
5
- timeout: 10.0s
6
- timeout method: signal
7
- timeout func_only: False
8
- collected 6 items
9
-
10
- test.py ...... [100%]
11
-
12
- - generated xml file: /home/linus/code/research_code_gen/code_agent/work_dir/dataset/annotations/annotation_127/pytest_report/report.xml -
13
- ============================== 6 passed in 2.26s ===============================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/canonical.py DELETED
@@ -1,422 +0,0 @@
1
- import math
2
- import numpy as np
3
- from typing import Iterator, Optional
4
- import torch
5
- from torch.utils.data.dataloader import _BaseDataLoaderIter
6
- from torch.utils.data import Dataset, _DatasetKind
7
- from torch.utils.data.distributed import DistributedSampler
8
- from operator import itemgetter
9
- import torch.distributed as dist
10
- import warnings
11
-
12
- __all__ = ['InfoBatch']
13
-
14
-
15
- def info_hack_indices(self):
16
- """
17
- This function is a "monkey patch" that replaces the default `__next__` method of PyTorch's internal `_BaseDataLoaderIter`.
18
- Its primary purpose is to intercept the batch of data *before* it is returned by the DataLoader's iterator.
19
-
20
- Paper Correspondence:
21
- - The paper describes updating scores H_t(z) for samples z within the current batch S_t (Section 2.3, Eq. 4) and
22
- rescaling their gradients (Section 2.3). To do this, the implementation needs to know which sample indices
23
- correspond to the data in the current batch.
24
- - Standard PyTorch DataLoaders do not expose the indices of the batch directly when iterating. This function
25
- "hacks" the iterator to solve this problem.
26
-
27
- Implementation Details (Not in Paper):
28
- - It calls the original `_next_data()` method to fetch the batch.
29
- - Crucially, if the dataset is an `InfoBatch` instance, `_next_data()` is expected to return a tuple of `(indices, data)`.
30
- This is achieved by modifying `InfoBatch.__getitem__`.
31
- - It then calls `self._dataset.set_active_indices(indices)` to inform the `InfoBatch` dataset wrapper about the
32
- indices of the samples currently being processed. This information is stored and later used in the `InfoBatch.update()`
33
- method to correctly associate losses with samples.
34
- - The function then returns only the `data` part of the batch, maintaining the expected behavior for the user's training loop.
35
- - The `_reset()` call with `type: ignore[call-arg]` is a workaround for a potential bug or type-hinting issue in PyTorch,
36
- as discussed in PyTorch issue #76750, where `_reset()` was found to be called without a required argument.
37
- """
38
- with torch.autograd.profiler.record_function(self._profile_name):
39
- if self._sampler_iter is None:
40
- # This internal method is called to reset the sampler iterator, e.g., at the beginning of an epoch.
41
- # The type: ignore comment suggests a known issue or mismatch with type hints in the PyTorch source.
42
- # See PyTorch GitHub issue #76750 for context.
43
- self._reset() # type: ignore[call-arg]
44
- if isinstance(self._dataset, InfoBatch):
45
- # If the dataset is an InfoBatch instance, we expect __getitem__ to return both indices and data.
46
- indices, data = self._next_data()
47
- else:
48
- # For standard datasets, it just returns data.
49
- data = self._next_data()
50
- self._num_yielded += 1
51
- if self._dataset_kind == _DatasetKind.Iterable and \
52
- self._IterableDataset_len_called is not None and \
53
- self._num_yielded > self._IterableDataset_len_called:
54
- warn_msg = ("Length of IterableDataset {} was reported to be {} (when accessing len(dataloader)), but {} "
55
- "samples have been fetched. ").format(self._dataset, self._IterableDataset_len_called,
56
- self._num_yielded)
57
- if self._num_workers > 0:
58
- warn_msg += ("For multiprocessing data-loading, this could be caused by not properly configuring the "
59
- "IterableDataset replica at each worker. Please see "
60
- "https://pytorch.org/docs/stable/data.html#torch.utils.data.IterableDataset for examples.")
61
- warnings.warn(warn_msg)
62
- if isinstance(self._dataset, InfoBatch):
63
- # This is the key step of the hack: we store the indices of the current batch
64
- # in the InfoBatch dataset object for later use in the `update` method.
65
- self._dataset.set_active_indices(indices)
66
- return data
67
-
68
- # This line performs the monkey-patching, replacing the original __next__ method
69
- # of the DataLoader iterator with our custom `info_hack_indices` function.
70
- # This makes the entire mechanism work without requiring users to modify their training loop.
71
- _BaseDataLoaderIter.__next__ = info_hack_indices
72
-
73
-
74
- @torch.no_grad()
75
- def concat_all_gather(tensor, dim=0):
76
- """
77
- Performs `all_gather` operation on the provided tensors across all distributed processes.
78
- This is a utility function for distributed training.
79
-
80
- Paper Correspondence:
81
- - The paper doesn't explicitly detail the distributed training implementation. However, to ensure that the
82
- sample scores `H_t(z)` are consistent across all workers, the loss values from the global batch (across all GPUs)
83
- must be collected. This function achieves that.
84
-
85
- Implementation Details (Not in Paper):
86
- - It gathers tensors from all processes in the distributed group and concatenates them.
87
- - This is used in `InfoBatch.update()` to gather the `(indices, loss_values)` pairs from all workers,
88
- so that the master `scores` tensor can be updated correctly with information from the entire global batch.
89
- """
90
- tensors_gather = [torch.ones_like(tensor)
91
- for _ in range(dist.get_world_size())]
92
- dist.all_gather(tensors_gather, tensor, async_op=False)
93
- output = torch.cat(tensors_gather, dim=dim)
94
- return output
95
-
96
-
97
- class InfoBatch(Dataset):
98
- """
99
- InfoBatch is a Dataset wrapper that implements the data pruning strategy described in the paper
100
- "INFOBATCH: LOSSLESS TRAINING SPEED UP BY UNBIASED DYNAMIC DATA PRUNING" (https://arxiv.org/pdf/2303.04947.pdf).
101
- It dynamically prunes less informative samples during training to accelerate convergence without sacrificing accuracy.
102
-
103
- .. note::
104
- The wrapped dataset is assumed to be a map-style dataset of constant size.
105
-
106
- Args:
107
- dataset: The original map-style dataset to be wrapped.
108
- num_epochs (int): The total number of training epochs. Used to schedule the annealing phase.
109
- prune_ratio (float, optional): The probability `r` of pruning a sample identified as "well-learned".
110
- Corresponds to `r` in Eq. 3 of the paper. Defaults to 0.5.
111
- delta (float, optional): The fraction of total epochs during which pruning is active. After `delta * num_epochs`,
112
- pruning stops (annealing phase). Corresponds to `δ` in Eq. 10. Defaults to 0.875.
113
- """
114
-
115
- def __init__(self, dataset: Dataset, num_epochs: int,
116
- prune_ratio: float = 0.5, delta: float = 0.875):
117
- self.dataset = dataset
118
- # `keep_ratio` corresponds to (1 - r) in the paper's formulation. It's the proportion of
119
- # well-learned samples that are kept, not pruned.
120
- self.keep_ratio = min(1.0, max(1e-1, 1.0 - prune_ratio))
121
- self.num_epochs = num_epochs
122
- # `delta` corresponds to the annealing hyperparameter δ from Section 2.4.
123
- self.delta = delta
124
-
125
- # `self.scores` stores the loss value H_t(z) for each sample z.
126
- # Paper Discrepancy: The paper (Section 2.3) mentions initializing scores to {1}.
127
- # Here, they are initialized to 3. This is a practical choice to set a high initial loss,
128
- # ensuring that no samples are considered "well-learned" and pruned before the first
129
- # forward pass and score update have occurred.
130
- self.scores = torch.ones(len(self.dataset)) * 3
131
-
132
- # `self.weights` stores the rescaling factor γ_t(z) for each sample. It is initialized to 1.
133
- self.weights = torch.ones(len(self.dataset))
134
- self.num_pruned_samples = 0
135
- # `self.cur_batch_index` is a temporary holder for the indices of the current batch,
136
- # populated by the `info_hack_indices` monkey patch.
137
- self.cur_batch_index = None
138
-
139
- def __getattr__(self, name):
140
- # This is a standard wrapper pattern. If an attribute is not found on InfoBatch,
141
- # it tries to retrieve it from the wrapped `self.dataset`. This makes InfoBatch
142
- # transparent for methods/attributes of the original dataset.
143
- return getattr(self.dataset, name)
144
-
145
- def set_active_indices(self, cur_batch_indices: torch.Tensor):
146
- """Stores the indices of the samples in the current batch."""
147
- self.cur_batch_index = cur_batch_indices
148
-
149
- def update(self, values):
150
- """
151
- Updates the scores of the samples in the last batch and returns the rescaled loss.
152
- This method should be called in the training loop with the loss tensor of the current batch.
153
-
154
- Paper Correspondence:
155
- - Score Update: Implements Eq. 4: H_{t+1}(z) = L(z) for samples z in the current batch S_t.
156
- - Expectation Rescaling: Implements the core idea from Section 2.3. It multiplies the incoming
157
- loss `values` by the stored `weights` (γ_t(z)), effectively rescaling the gradients during backpropagation.
158
- The objective becomes E_{z in S_t}[γ_t(z)L(z, θ)], as in Eq. 6.
159
- """
160
- assert isinstance(values, torch.Tensor)
161
- batch_size = values.shape[0]
162
- assert len(self.cur_batch_index) == batch_size, 'The number of provided indices does not match the batch size.'
163
- device = values.device
164
- weights = self.weights[self.cur_batch_index].to(device)
165
- indices = self.cur_batch_index.to(device)
166
- loss_val = values.detach().clone()
167
- # Clear the indices after use.
168
- self.cur_batch_index = []
169
-
170
- # Handle distributed training by gathering losses and indices from all workers.
171
- if dist.is_available() and dist.is_initialized():
172
- # Concatenate indices and losses for efficient gathering.
173
- iv = torch.cat([indices.view(1, -1), loss_val.view(1, -1)], dim=0)
174
- # Gather from all processes.
175
- iv_whole_group = concat_all_gather(iv, 1)
176
- indices = iv_whole_group[0]
177
- loss_val = iv_whole_group[1]
178
-
179
- # Update the scores for the samples in the global batch.
180
- self.scores[indices.cpu().long()] = loss_val.cpu()
181
-
182
- # Apply expectation rescaling: multiply the loss by the per-sample weight.
183
- # When backpropagation occurs, this will scale the gradients accordingly.
184
- values.mul_(weights)
185
-
186
- # Return the mean of the rescaled loss for the batch.
187
- return values.mean()
188
-
189
- def __len__(self):
190
- """Returns the size of the original, unpruned dataset."""
191
- return len(self.dataset)
192
-
193
- def __getitem__(self, index):
194
- """
195
- Overrides `__getitem__` to return both the data and its index.
196
-
197
- Implementation Details (Not in Paper):
198
- - This modification is essential for the `info_hack_indices` monkey patch to work.
199
- - The DataLoader's collate function will receive a list of `(index, data_tuple)` pairs.
200
- - The default collate function can handle this, creating a batch of indices and a batch of data.
201
- - Our monkey patch then intercepts this pair, passes the indices to the InfoBatch object,
202
- and returns only the data batch to the user.
203
- """
204
- return index, self.dataset[index]
205
-
206
- def prune(self):
207
- """
208
- Implements the soft pruning and weight rescaling logic for one epoch.
209
-
210
- Paper Correspondence:
211
- - This method directly implements the soft pruning policy from Eq. 3: P_t(z) = r if H_t(z) < H̄_t, and 0 otherwise.
212
- - It also sets the weights for expectation rescaling as described in Section 2.3.
213
- """
214
- # 1. Identify well-learned samples: H_t(z) < H̄_t (mean of all scores).
215
- well_learned_mask = (self.scores < self.scores.mean()).numpy()
216
- well_learned_indices = np.where(well_learned_mask)[0]
217
- remained_indices = np.where(~well_learned_mask)[0].tolist()
218
-
219
- # 2. Soft Pruning: Randomly select a `keep_ratio` (1-r) fraction of well-learned samples to keep for training.
220
- selected_indices = np.random.choice(well_learned_indices, int(
221
- self.keep_ratio * len(well_learned_indices)), replace=False)
222
-
223
- # 3. Expectation Rescaling: Reset all weights to 1, then scale up the weights of the kept "well-learned" samples.
224
- self.reset_weights()
225
- if len(selected_indices) > 0:
226
- # The weight γ_t(z) is set to 1 / (1 - r) for these samples.
227
- self.weights[selected_indices] = 1 / self.keep_ratio
228
- remained_indices.extend(selected_indices)
229
-
230
- self.num_pruned_samples += len(self.dataset) - len(remained_indices)
231
- np.random.shuffle(remained_indices)
232
-
233
- # Return the final list of indices to be used for training in the upcoming epoch.
234
- return remained_indices
235
-
236
- @property
237
- def sampler(self):
238
- """Provides a compatible sampler for the DataLoader."""
239
- sampler = IBSampler(self)
240
- if dist.is_available() and dist.is_initialized():
241
- # If in a distributed environment, wrap the sampler for data parallelism.
242
- sampler = DistributedIBSampler(sampler)
243
- return sampler
244
-
245
- def no_prune(self):
246
- """
247
- Returns a shuffled list of all sample indices. Used during the annealing phase
248
- when pruning is turned off.
249
- """
250
- samples_indices = list(range(len(self)))
251
- np.random.shuffle(samples_indices)
252
- return samples_indices
253
-
254
- def mean_score(self):
255
- """Returns the mean of all current sample scores."""
256
- return self.scores.mean()
257
-
258
- def get_weights(self, indexes):
259
- """Returns the rescaling weights for a given set of indices."""
260
- return self.weights[indexes]
261
-
262
- def get_pruned_count(self):
263
- """Returns the total number of samples pruned so far."""
264
- return self.num_pruned_samples
265
-
266
- @property
267
- def stop_prune(self):
268
- """
269
- Calculates the epoch number at which to stop pruning, based on the annealing schedule.
270
- Corresponds to δ * C from Section 2.4.
271
- """
272
- return self.num_epochs * self.delta
273
-
274
- def reset_weights(self):
275
- """Resets all sample weights to 1."""
276
- self.weights[:] = 1
277
-
278
-
279
- class IBSampler(object):
280
- """
281
- InfoBatch Sampler (IBSampler).
282
- This is a custom sampler that generates the list of indices for each epoch.
283
- It orchestrates the pruning and annealing schedule.
284
-
285
- Implementation Details (Not in Paper):
286
- - This class acts as a PyTorch sampler by implementing `__iter__` and `__len__`.
287
- - It is stateful, tracking the number of `iterations` (epochs).
288
- """
289
- def __init__(self, dataset: InfoBatch):
290
- self.dataset = dataset
291
- self.stop_prune = dataset.stop_prune
292
- self.iterations = 0
293
- self.sample_indices = None
294
- self.iter_obj = None
295
- self.reset()
296
-
297
- def __getitem__(self, idx):
298
- return self.sample_indices[idx]
299
-
300
- def reset(self):
301
- """
302
- Resets the sampler's state at the beginning of each epoch.
303
- This is where the decision to prune or not is made.
304
-
305
- Paper Correspondence:
306
- - This method implements the annealing logic from Eq. 10.
307
- - If `self.iterations > self.stop_prune`, it calls `self.dataset.no_prune()`, switching to the full dataset.
308
- - Otherwise, it calls `self.dataset.prune()` to get a pruned set of indices.
309
- """
310
- np.random.seed(self.iterations) # For reproducibility of the shuffle.
311
- if self.iterations > self.stop_prune:
312
- # Annealing phase: stop pruning and use the full dataset.
313
- if self.iterations == self.stop_prune + 1:
314
- # On the first epoch of annealing, reset weights to 1.
315
- self.dataset.reset_weights()
316
- self.sample_indices = self.dataset.no_prune()
317
- else:
318
- # Pruning phase: get a new set of pruned indices for this epoch.
319
- self.sample_indices = self.dataset.prune()
320
- self.iter_obj = iter(self.sample_indices)
321
- self.iterations += 1
322
-
323
- def __next__(self):
324
- """Returns the next index from the iterator."""
325
- return next(self.iter_obj) # may raise StopIteration
326
-
327
- def __len__(self):
328
- """Returns the number of samples for the current epoch (which can change)."""
329
- return len(self.sample_indices)
330
-
331
- def __iter__(self):
332
- """
333
- Called by the DataLoader at the beginning of each epoch.
334
- Resets the state and returns itself as the iterator.
335
- """
336
- self.reset()
337
- return self
338
-
339
-
340
- class DistributedIBSampler(DistributedSampler):
341
- """
342
- A distributed wrapper for `IBSampler`.
343
- This ensures that when using multiple GPUs/processes, each process receives a unique,
344
- non-overlapping subset of the indices generated by `IBSampler`.
345
-
346
- Implementation Details (Not in Paper):
347
- - It inherits from PyTorch's `DistributedSampler` and adapts its logic.
348
- - It uses a nested `DatasetFromSampler` class to make the `IBSampler` compatible with the
349
- `DistributedSampler`'s expectation of a `Dataset` object. This is a common pattern for
350
- wrapping dynamic samplers in a distributed setting.
351
- - The `__iter__` method contains the core logic for splitting the epoch's indices among the ranks.
352
- """
353
- class DatasetFromSampler(Dataset):
354
- """A helper class to wrap a sampler to behave like a dataset."""
355
- def __init__(self, sampler: IBSampler):
356
- self.dataset = sampler
357
-
358
- def reset(self, ):
359
- self.dataset.reset()
360
-
361
- def __len__(self):
362
- return len(self.dataset)
363
-
364
- def __getitem__(self, index: int):
365
- """Gets an element from the sampler's current index list."""
366
- return self.dataset[index]
367
-
368
- def __init__(self, dataset: IBSampler, num_replicas: Optional[int] = None,
369
- rank: Optional[int] = None, shuffle: bool = True,
370
- seed: int = 0, drop_last: bool = True) -> None:
371
- # The 'dataset' here is actually our IBSampler, which we wrap.
372
- sampler = self.DatasetFromSampler(dataset)
373
- super(DistributedIBSampler, self).__init__(
374
- sampler, num_replicas, rank, shuffle, seed, drop_last)
375
- self.sampler = sampler
376
- self.dataset = sampler.dataset.dataset # The actual, original dataset.
377
- self.iter_obj = None
378
-
379
- def __iter__(self) -> Iterator[int]:
380
- """
381
- Generates the indices for the current process/rank for one epoch.
382
- """
383
- # 1. Reset the underlying IBSampler to generate the full list of indices for this epoch.
384
- self.sampler.reset()
385
-
386
- # 2. Standard DistributedSampler logic to calculate how many samples this rank should handle.
387
- if self.drop_last and len(self.sampler) % self.num_replicas != 0:
388
- self.num_samples = math.ceil(
389
- (len(self.sampler) - self.num_replicas) / self.num_replicas
390
- )
391
- else:
392
- self.num_samples = math.ceil(
393
- len(self.sampler) / self.num_replicas)
394
- self.total_size = self.num_samples * self.num_replicas
395
-
396
- # 3. Get the full list of indices from the underlying sampler.
397
- if self.shuffle:
398
- # Deterministically shuffle the full list of indices based on the epoch.
399
- g = torch.Generator()
400
- g.manual_seed(self.seed + self.epoch)
401
- indices = torch.randperm(len(self.sampler), generator=g).tolist()
402
- else:
403
- indices = list(range(len(self.sampler)))
404
-
405
- # 4. Pad or truncate the index list to be evenly divisible by the number of replicas.
406
- if not self.drop_last:
407
- padding_size = self.total_size - len(indices)
408
- if padding_size <= len(indices):
409
- indices += indices[:padding_size]
410
- else:
411
- indices += (indices * math.ceil(padding_size /
412
- len(indices)))[:padding_size]
413
- else:
414
- indices = indices[:self.total_size]
415
- assert len(indices) == self.total_size
416
-
417
- # 5. Select the subset of indices for the current rank.
418
- indices = indices[self.rank:self.total_size:self.num_replicas]
419
-
420
- # 6. Return an iterator over the original indices (from the sampler) that correspond to the shuffled, sliced indices.
421
- self.iter_obj = iter(itemgetter(*indices)(self.sampler))
422
- return self.iter_obj
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/function_info.json DELETED
@@ -1,672 +0,0 @@
1
- [
2
- {
3
- "function_name": "info_hack_indices",
4
- "file_path": "infobatch/infobatch.py",
5
- "function_calls": [
6
- {
7
- "function_call_name": "torch.autograd.profiler.record_function",
8
- "functionality": "A context manager that adds a label to a block of code in the profiler's output.",
9
- "input": "self._profile_name",
10
- "output": "A context manager.",
11
- "location_or_namespace": "torch.autograd.profiler"
12
- },
13
- {
14
- "function_call_name": "_BaseDataLoaderIter._reset",
15
- "functionality": "Resets the state of the data loader iterator, typically at the beginning of an epoch.",
16
- "input": "",
17
- "output": "None",
18
- "location_or_namespace": "torch.utils.data.dataloader"
19
- },
20
- {
21
- "function_call_name": "isinstance",
22
- "functionality": "Checks if an object is an instance of a class or of a subclass thereof.",
23
- "input": "(self._dataset, InfoBatch)",
24
- "output": "bool",
25
- "location_or_namespace": "builtins"
26
- },
27
- {
28
- "function_call_name": "_BaseDataLoaderIter._next_data",
29
- "functionality": "Fetches the next batch of data from the worker processes.",
30
- "input": "",
31
- "output": "A tuple of (indices, data) if the dataset is InfoBatch, otherwise just data.",
32
- "location_or_namespace": "torch.utils.data.dataloader"
33
- },
34
- {
35
- "function_call_name": "warnings.warn",
36
- "functionality": "Issues a warning message.",
37
- "input": "warn_msg",
38
- "output": "None",
39
- "location_or_namespace": "warnings"
40
- },
41
- {
42
- "function_call_name": "InfoBatch.set_active_indices",
43
- "functionality": "Stores the indices of the samples in the current batch within the InfoBatch object.",
44
- "input": "indices",
45
- "output": "None",
46
- "location_or_namespace": "infobatch/infobatch.py"
47
- }
48
- ]
49
- },
50
- {
51
- "function_name": "concat_all_gather",
52
- "file_path": "infobatch/infobatch.py",
53
- "function_calls": [
54
- {
55
- "function_call_name": "torch.distributed.get_world_size",
56
- "functionality": "Returns the total number of processes in the current distributed group.",
57
- "input": "",
58
- "output": "int",
59
- "location_or_namespace": "torch.distributed"
60
- },
61
- {
62
- "function_call_name": "range",
63
- "functionality": "Generates a sequence of numbers.",
64
- "input": "dist.get_world_size()",
65
- "output": "An immutable sequence of numbers.",
66
- "location_or_namespace": "builtins"
67
- },
68
- {
69
- "function_call_name": "torch.ones_like",
70
- "functionality": "Returns a tensor filled with the scalar value 1, with the same size as the input tensor.",
71
- "input": "tensor",
72
- "output": "torch.Tensor",
73
- "location_or_namespace": "torch"
74
- },
75
- {
76
- "function_call_name": "torch.distributed.all_gather",
77
- "functionality": "Gathers tensors from the whole group in a list.",
78
- "input": "tensors_gather, tensor, async_op=False",
79
- "output": "None",
80
- "location_or_namespace": "torch.distributed"
81
- },
82
- {
83
- "function_call_name": "torch.cat",
84
- "functionality": "Concatenates the given sequence of tensors in the given dimension.",
85
- "input": "tensors_gather, dim=dim",
86
- "output": "torch.Tensor",
87
- "location_or_namespace": "torch"
88
- }
89
- ]
90
- },
91
- {
92
- "function_name": "InfoBatch.__init__",
93
- "file_path": "infobatch/infobatch.py",
94
- "function_calls": [
95
- {
96
- "function_call_name": "min",
97
- "functionality": "Returns the smallest of its arguments.",
98
- "input": "1.0, max(1e-1, 1.0 - prune_ratio)",
99
- "output": "float",
100
- "location_or_namespace": "builtins"
101
- },
102
- {
103
- "function_call_name": "max",
104
- "functionality": "Returns the largest of its arguments.",
105
- "input": "1e-1, 1.0 - prune_ratio",
106
- "output": "float",
107
- "location_or_namespace": "builtins"
108
- },
109
- {
110
- "function_call_name": "len",
111
- "functionality": "Returns the number of items in an object.",
112
- "input": "self.dataset",
113
- "output": "int",
114
- "location_or_namespace": "builtins"
115
- },
116
- {
117
- "function_call_name": "torch.ones",
118
- "functionality": "Returns a tensor filled with the scalar value 1, of the given size.",
119
- "input": "len(self.dataset)",
120
- "output": "torch.Tensor",
121
- "location_or_namespace": "torch"
122
- }
123
- ]
124
- },
125
- {
126
- "function_name": "InfoBatch.__getattr__",
127
- "file_path": "infobatch/infobatch.py",
128
- "function_calls": [
129
- {
130
- "function_call_name": "getattr",
131
- "functionality": "Returns the value of the named attribute of an object.",
132
- "input": "self.dataset, name",
133
- "output": "Any",
134
- "location_or_namespace": "builtins"
135
- }
136
- ]
137
- },
138
- {
139
- "function_name": "InfoBatch.set_active_indices",
140
- "file_path": "infobatch/infobatch.py",
141
- "function_calls": []
142
- },
143
- {
144
- "function_name": "InfoBatch.update",
145
- "file_path": "infobatch/infobatch.py",
146
- "function_calls": [
147
- {
148
- "function_call_name": "isinstance",
149
- "functionality": "Checks if an object is an instance of a class or of a subclass thereof.",
150
- "input": "(values, torch.Tensor)",
151
- "output": "bool",
152
- "location_or_namespace": "builtins"
153
- },
154
- {
155
- "function_call_name": "len",
156
- "functionality": "Returns the number of items in an object.",
157
- "input": "self.cur_batch_index",
158
- "output": "int",
159
- "location_or_namespace": "builtins"
160
- },
161
- {
162
- "function_call_name": "torch.Tensor.to",
163
- "functionality": "Moves and/or casts the tensor to a specified device and/or dtype.",
164
- "input": "device",
165
- "output": "torch.Tensor",
166
- "location_or_namespace": "torch"
167
- },
168
- {
169
- "function_call_name": "torch.Tensor.detach",
170
- "functionality": "Returns a new tensor, detached from the current graph. The result will never require gradient.",
171
- "input": "",
172
- "output": "torch.Tensor",
173
- "location_or_namespace": "torch"
174
- },
175
- {
176
- "function_call_name": "torch.Tensor.clone",
177
- "functionality": "Returns a copy of the tensor with the same size and data type.",
178
- "input": "",
179
- "output": "torch.Tensor",
180
- "location_or_namespace": "torch"
181
- },
182
- {
183
- "function_call_name": "torch.distributed.is_available",
184
- "functionality": "Checks if the distributed package is available.",
185
- "input": "",
186
- "output": "bool",
187
- "location_or_namespace": "torch.distributed"
188
- },
189
- {
190
- "function_call_name": "torch.distributed.is_initialized",
191
- "functionality": "Checks if the default process group has been initialized.",
192
- "input": "",
193
- "output": "bool",
194
- "location_or_namespace": "torch.distributed"
195
- },
196
- {
197
- "function_call_name": "torch.cat",
198
- "functionality": "Concatenates the given sequence of tensors in the given dimension.",
199
- "input": "[indices.view(1, -1), loss_val.view(1, -1)], dim=0",
200
- "output": "torch.Tensor",
201
- "location_or_namespace": "torch"
202
- },
203
- {
204
- "function_call_name": "concat_all_gather",
205
- "functionality": "Performs `all_gather` operation on the provided tensors across all distributed processes.",
206
- "input": "iv, 1",
207
- "output": "torch.Tensor",
208
- "location_or_namespace": "infobatch/infobatch.py"
209
- },
210
- {
211
- "function_call_name": "torch.Tensor.cpu",
212
- "functionality": "Returns a copy of this object in CPU memory.",
213
- "input": "",
214
- "output": "torch.Tensor",
215
- "location_or_namespace": "torch"
216
- },
217
- {
218
- "function_call_name": "torch.Tensor.long",
219
- "functionality": "Casts this tensor to `long` type.",
220
- "input": "",
221
- "output": "torch.Tensor",
222
- "location_or_namespace": "torch"
223
- },
224
- {
225
- "function_call_name": "torch.Tensor.mul_",
226
- "functionality": "In-place multiplication of the tensor by a scalar or another tensor.",
227
- "input": "weights",
228
- "output": "torch.Tensor",
229
- "location_or_namespace": "torch"
230
- },
231
- {
232
- "function_call_name": "torch.Tensor.mean",
233
- "functionality": "Returns the mean value of all elements in the input tensor.",
234
- "input": "",
235
- "output": "torch.Tensor",
236
- "location_or_namespace": "torch"
237
- }
238
- ]
239
- },
240
- {
241
- "function_name": "InfoBatch.__len__",
242
- "file_path": "infobatch/infobatch.py",
243
- "function_calls": [
244
- {
245
- "function_call_name": "len",
246
- "functionality": "Returns the number of items in an object.",
247
- "input": "self.dataset",
248
- "output": "int",
249
- "location_or_namespace": "builtins"
250
- }
251
- ]
252
- },
253
- {
254
- "function_name": "InfoBatch.__getitem__",
255
- "file_path": "infobatch/infobatch.py",
256
- "function_calls": []
257
- },
258
- {
259
- "function_name": "InfoBatch.prune",
260
- "file_path": "infobatch/infobatch.py",
261
- "function_calls": [
262
- {
263
- "function_call_name": "torch.Tensor.mean",
264
- "functionality": "Returns the mean value of all elements in the input tensor.",
265
- "input": "",
266
- "output": "torch.Tensor",
267
- "location_or_namespace": "torch"
268
- },
269
- {
270
- "function_call_name": "torch.Tensor.numpy",
271
- "functionality": "Returns the tensor as a NumPy ndarray.",
272
- "input": "",
273
- "output": "numpy.ndarray",
274
- "location_or_namespace": "torch"
275
- },
276
- {
277
- "function_call_name": "numpy.where",
278
- "functionality": "Return elements chosen from x or y depending on condition.",
279
- "input": "well_learned_mask",
280
- "output": "tuple of numpy.ndarray",
281
- "location_or_namespace": "numpy"
282
- },
283
- {
284
- "function_call_name": "list.tolist",
285
- "functionality": "Converts a NumPy array to a Python list.",
286
- "input": "",
287
- "output": "list",
288
- "location_or_namespace": "numpy"
289
- },
290
- {
291
- "function_call_name": "numpy.random.choice",
292
- "functionality": "Generates a random sample from a given 1-D array.",
293
- "input": "well_learned_indices, int(self.keep_ratio * len(well_learned_indices)), replace=False",
294
- "output": "numpy.ndarray",
295
- "location_or_namespace": "numpy.random"
296
- },
297
- {
298
- "function_call_name": "int",
299
- "functionality": "Converts a number or string to an integer.",
300
- "input": "self.keep_ratio * len(well_learned_indices)",
301
- "output": "int",
302
- "location_or_namespace": "builtins"
303
- },
304
- {
305
- "function_call_name": "len",
306
- "functionality": "Returns the number of items in an object.",
307
- "input": "well_learned_indices or remained_indices",
308
- "output": "int",
309
- "location_or_namespace": "builtins"
310
- },
311
- {
312
- "function_call_name": "InfoBatch.reset_weights",
313
- "functionality": "Resets all sample weights to 1.",
314
- "input": "",
315
- "output": "None",
316
- "location_or_namespace": "infobatch/infobatch.py"
317
- },
318
- {
319
- "function_call_name": "list.extend",
320
- "functionality": "Appends elements from an iterable to the end of the list.",
321
- "input": "selected_indices",
322
- "output": "None",
323
- "location_or_namespace": "builtins"
324
- },
325
- {
326
- "function_call_name": "numpy.random.shuffle",
327
- "functionality": "Modify a sequence in-place by shuffling its contents.",
328
- "input": "remained_indices",
329
- "output": "None",
330
- "location_or_namespace": "numpy.random"
331
- }
332
- ]
333
- },
334
- {
335
- "function_name": "InfoBatch.sampler",
336
- "file_path": "infobatch/infobatch.py",
337
- "function_calls": [
338
- {
339
- "function_call_name": "IBSampler",
340
- "functionality": "Initializes the InfoBatch Sampler.",
341
- "input": "self",
342
- "output": "IBSampler object",
343
- "location_or_namespace": "infobatch/infobatch.py"
344
- },
345
- {
346
- "function_call_name": "torch.distributed.is_available",
347
- "functionality": "Checks if the distributed package is available.",
348
- "input": "",
349
- "output": "bool",
350
- "location_or_namespace": "torch.distributed"
351
- },
352
- {
353
- "function_call_name": "torch.distributed.is_initialized",
354
- "functionality": "Checks if the default process group has been initialized.",
355
- "input": "",
356
- "output": "bool",
357
- "location_or_namespace": "torch.distributed"
358
- },
359
- {
360
- "function_call_name": "DistributedIBSampler",
361
- "functionality": "Initializes the Distributed InfoBatch Sampler.",
362
- "input": "sampler",
363
- "output": "DistributedIBSampler object",
364
- "location_or_namespace": "infobatch/infobatch.py"
365
- }
366
- ]
367
- },
368
- {
369
- "function_name": "InfoBatch.no_prune",
370
- "file_path": "infobatch/infobatch.py",
371
- "function_calls": [
372
- {
373
- "function_call_name": "list",
374
- "functionality": "Creates a list from an iterable.",
375
- "input": "range(len(self))",
376
- "output": "list",
377
- "location_or_namespace": "builtins"
378
- },
379
- {
380
- "function_call_name": "range",
381
- "functionality": "Generates a sequence of numbers.",
382
- "input": "len(self)",
383
- "output": "An immutable sequence of numbers.",
384
- "location_or_namespace": "builtins"
385
- },
386
- {
387
- "function_call_name": "len",
388
- "functionality": "Returns the number of items in an object.",
389
- "input": "self",
390
- "output": "int",
391
- "location_or_namespace": "builtins"
392
- },
393
- {
394
- "function_call_name": "numpy.random.shuffle",
395
- "functionality": "Modify a sequence in-place by shuffling its contents.",
396
- "input": "samples_indices",
397
- "output": "None",
398
- "location_or_namespace": "numpy.random"
399
- }
400
- ]
401
- },
402
- {
403
- "function_name": "InfoBatch.mean_score",
404
- "file_path": "infobatch/infobatch.py",
405
- "function_calls": [
406
- {
407
- "function_call_name": "torch.Tensor.mean",
408
- "functionality": "Returns the mean value of all elements in the input tensor.",
409
- "input": "",
410
- "output": "torch.Tensor",
411
- "location_or_namespace": "torch"
412
- }
413
- ]
414
- },
415
- {
416
- "function_name": "InfoBatch.get_weights",
417
- "file_path": "infobatch/infobatch.py",
418
- "function_calls": []
419
- },
420
- {
421
- "function_name": "InfoBatch.get_pruned_count",
422
- "file_path": "infobatch/infobatch.py",
423
- "function_calls": []
424
- },
425
- {
426
- "function_name": "InfoBatch.stop_prune",
427
- "file_path": "infobatch/infobatch.py",
428
- "function_calls": []
429
- },
430
- {
431
- "function_name": "InfoBatch.reset_weights",
432
- "file_path": "infobatch/infobatch.py",
433
- "function_calls": []
434
- },
435
- {
436
- "function_name": "IBSampler.__init__",
437
- "file_path": "infobatch/infobatch.py",
438
- "function_calls": [
439
- {
440
- "function_call_name": "IBSampler.reset",
441
- "functionality": "Resets the sampler's state at the beginning of each epoch, deciding whether to prune or not.",
442
- "input": "",
443
- "output": "None",
444
- "location_or_namespace": "infobatch/infobatch.py"
445
- }
446
- ]
447
- },
448
- {
449
- "function_name": "IBSampler.__getitem__",
450
- "file_path": "infobatch/infobatch.py",
451
- "function_calls": []
452
- },
453
- {
454
- "function_name": "IBSampler.reset",
455
- "file_path": "infobatch/infobatch.py",
456
- "function_calls": [
457
- {
458
- "function_call_name": "numpy.random.seed",
459
- "functionality": "Seed the generator.",
460
- "input": "self.iterations",
461
- "output": "None",
462
- "location_or_namespace": "numpy.random"
463
- },
464
- {
465
- "function_call_name": "InfoBatch.reset_weights",
466
- "functionality": "Resets all sample weights to 1.",
467
- "input": "",
468
- "output": "None",
469
- "location_or_namespace": "infobatch/infobatch.py"
470
- },
471
- {
472
- "function_call_name": "InfoBatch.no_prune",
473
- "functionality": "Returns a shuffled list of all sample indices.",
474
- "input": "",
475
- "output": "list",
476
- "location_or_namespace": "infobatch/infobatch.py"
477
- },
478
- {
479
- "function_call_name": "InfoBatch.prune",
480
- "functionality": "Implements the soft pruning and weight rescaling logic for one epoch.",
481
- "input": "",
482
- "output": "list",
483
- "location_or_namespace": "infobatch/infobatch.py"
484
- },
485
- {
486
- "function_call_name": "iter",
487
- "functionality": "Returns an iterator object.",
488
- "input": "self.sample_indices",
489
- "output": "iterator",
490
- "location_or_namespace": "builtins"
491
- }
492
- ]
493
- },
494
- {
495
- "function_name": "IBSampler.__next__",
496
- "file_path": "infobatch/infobatch.py",
497
- "function_calls": [
498
- {
499
- "function_call_name": "next",
500
- "functionality": "Retrieve the next item from the iterator by calling its __next__() method.",
501
- "input": "self.iter_obj",
502
- "output": "Any",
503
- "location_or_namespace": "builtins"
504
- }
505
- ]
506
- },
507
- {
508
- "function_name": "IBSampler.__len__",
509
- "file_path": "infobatch/infobatch.py",
510
- "function_calls": [
511
- {
512
- "function_call_name": "len",
513
- "functionality": "Returns the number of items in an object.",
514
- "input": "self.sample_indices",
515
- "output": "int",
516
- "location_or_namespace": "builtins"
517
- }
518
- ]
519
- },
520
- {
521
- "function_name": "IBSampler.__iter__",
522
- "file_path": "infobatch/infobatch.py",
523
- "function_calls": [
524
- {
525
- "function_call_name": "IBSampler.reset",
526
- "functionality": "Resets the sampler's state at the beginning of each epoch, deciding whether to prune or not.",
527
- "input": "",
528
- "output": "None",
529
- "location_or_namespace": "infobatch/infobatch.py"
530
- }
531
- ]
532
- },
533
- {
534
- "function_name": "DistributedIBSampler.DatasetFromSampler.__init__",
535
- "file_path": "infobatch/infobatch.py",
536
- "function_calls": []
537
- },
538
- {
539
- "function_name": "DistributedIBSampler.DatasetFromSampler.reset",
540
- "file_path": "infobatch/infobatch.py",
541
- "function_calls": [
542
- {
543
- "function_call_name": "IBSampler.reset",
544
- "functionality": "Resets the sampler's state at the beginning of each epoch, deciding whether to prune or not.",
545
- "input": "",
546
- "output": "None",
547
- "location_or_namespace": "infobatch/infobatch.py"
548
- }
549
- ]
550
- },
551
- {
552
- "function_name": "DistributedIBSampler.DatasetFromSampler.__len__",
553
- "file_path": "infobatch/infobatch.py",
554
- "function_calls": [
555
- {
556
- "function_call_name": "len",
557
- "functionality": "Returns the number of items in an object.",
558
- "input": "self.dataset",
559
- "output": "int",
560
- "location_or_namespace": "builtins"
561
- }
562
- ]
563
- },
564
- {
565
- "function_name": "DistributedIBSampler.DatasetFromSampler.__getitem__",
566
- "file_path": "infobatch/infobatch.py",
567
- "function_calls": []
568
- },
569
- {
570
- "function_name": "DistributedIBSampler.__init__",
571
- "file_path": "infobatch/infobatch.py",
572
- "function_calls": [
573
- {
574
- "function_call_name": "DistributedIBSampler.DatasetFromSampler",
575
- "functionality": "Initializes the helper class to wrap a sampler to behave like a dataset.",
576
- "input": "dataset",
577
- "output": "DatasetFromSampler object",
578
- "location_or_namespace": "infobatch/infobatch.py"
579
- },
580
- {
581
- "function_call_name": "torch.utils.data.distributed.DistributedSampler.__init__",
582
- "functionality": "Initializes the parent DistributedSampler class.",
583
- "input": "sampler, num_replicas, rank, shuffle, seed, drop_last",
584
- "output": "None",
585
- "location_or_namespace": "torch.utils.data.distributed"
586
- }
587
- ]
588
- },
589
- {
590
- "function_name": "DistributedIBSampler.__iter__",
591
- "file_path": "infobatch/infobatch.py",
592
- "function_calls": [
593
- {
594
- "function_call_name": "DistributedIBSampler.DatasetFromSampler.reset",
595
- "functionality": "Resets the state of the wrapped IBSampler.",
596
- "input": "",
597
- "output": "None",
598
- "location_or_namespace": "infobatch/infobatch.py"
599
- },
600
- {
601
- "function_call_name": "len",
602
- "functionality": "Returns the number of items in an object.",
603
- "input": "self.sampler",
604
- "output": "int",
605
- "location_or_namespace": "builtins"
606
- },
607
- {
608
- "function_call_name": "math.ceil",
609
- "functionality": "Rounds a number up to the nearest integer.",
610
- "input": "...",
611
- "output": "int",
612
- "location_or_namespace": "math"
613
- },
614
- {
615
- "function_call_name": "torch.Generator",
616
- "functionality": "Creates and returns a generator object that manages the state of a random number generator.",
617
- "input": "",
618
- "output": "torch.Generator object",
619
- "location_or_namespace": "torch"
620
- },
621
- {
622
- "function_call_name": "torch.Generator.manual_seed",
623
- "functionality": "Sets the seed for generating random numbers.",
624
- "input": "self.seed + self.epoch",
625
- "output": "torch.Generator object",
626
- "location_or_namespace": "torch"
627
- },
628
- {
629
- "function_call_name": "torch.randperm",
630
- "functionality": "Returns a random permutation of integers from 0 to n - 1.",
631
- "input": "len(self.sampler), generator=g",
632
- "output": "torch.Tensor",
633
- "location_or_namespace": "torch"
634
- },
635
- {
636
- "function_call_name": "list.tolist",
637
- "functionality": "Converts a tensor to a (nested) list.",
638
- "input": "",
639
- "output": "list",
640
- "location_or_namespace": "torch"
641
- },
642
- {
643
- "function_call_name": "list",
644
- "functionality": "Creates a list from an iterable.",
645
- "input": "range(len(self.sampler))",
646
- "output": "list",
647
- "location_or_namespace": "builtins"
648
- },
649
- {
650
- "function_call_name": "range",
651
- "functionality": "Generates a sequence of numbers.",
652
- "input": "len(self.sampler)",
653
- "output": "An immutable sequence of numbers.",
654
- "location_or_namespace": "builtins"
655
- },
656
- {
657
- "function_call_name": "iter",
658
- "functionality": "Returns an iterator object.",
659
- "input": "itemgetter(*indices)(self.sampler)",
660
- "output": "iterator",
661
- "location_or_namespace": "builtins"
662
- },
663
- {
664
- "function_call_name": "operator.itemgetter",
665
- "functionality": "Return a callable object that fetches item from its operand.",
666
- "input": "*indices",
667
- "output": "A callable itemgetter object.",
668
- "location_or_namespace": "operator"
669
- }
670
- ]
671
- }
672
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/instruction.txt DELETED
@@ -1,284 +0,0 @@
1
- # Code Generation Instruction: InfoBatch Dynamic Data Pruning
2
-
3
- ## Goal:
4
- Implement the key components of the InfoBatch algorithm, a framework for accelerating deep learning training through unbiased dynamic data pruning, as described in the paper "INFOBATCH: LOSSLESS TRAINING SPEED UP BY UNBIASED DYNAMIC DATA PRUNING". This involves creating a dataset wrapper to manage sample scores and pruning, a custom sampler to control the training schedule, and utilities for distributed training.
5
-
6
- ---
7
-
8
- ### **Global Functions**
9
-
10
- ---
11
-
12
- #### **Instruction 1: Implement DataLoader Iterator Monkey-Patch**
13
-
14
- * **Functionality Description:** Implement a function intended to replace the `__next__` method of a standard data loader iterator (`_BaseDataLoaderIter`). This "monkey-patch" is crucial for intercepting the batch data before it's returned to the training loop. Its purpose is to extract the indices of the samples in the current batch and pass them to the `InfoBatch` dataset wrapper. This mechanism enables the `update` method to correctly associate loss values with their corresponding samples, a requirement not supported by default data loaders. The function should then return only the data portion of the batch, preserving the expected behavior for the user.
15
- * **Expected Function Name:** `info_hack_indices`
16
- * **Input:**
17
- * `self` (object): The data loader iterator instance (`_BaseDataLoaderIter`).
18
- * **Output:**
19
- * `data` (object): The batch of data, ready for model processing.
20
-
21
- ---
22
-
23
- #### **Instruction 2: Implement Distributed Tensor Gathering**
24
-
25
- * **Functionality Description:** Implement a utility function for distributed training environments. The function should gather lists of data (represented as tensors) from all parallel processes and concatenate them into a single, unified list. This is essential for ensuring that operations like score updates are based on information from the entire global batch across all workers.
26
- * **Expected Function Name:** `concat_all_gather`
27
- * **Input:**
28
- * `tensor` (list of list of float): A list-based representation of a 2D tensor on a single process.
29
- * `dim` (int): The dimension along which to concatenate the gathered lists (e.g., `0` for rows, `1` for columns).
30
- * **Output:**
31
- * `output` (list of list of float): The final list after gathering and concatenating the data from all processes.
32
-
33
- ---
34
-
35
- ### **`InfoBatch` Class**
36
-
37
- ---
38
-
39
- #### **Instruction 3: Implement InfoBatch Dataset Wrapper Initialization**
40
-
41
- * **Functionality Description:** Implement the initialization logic for the `InfoBatch` dataset wrapper. This class is central to the algorithm and is responsible for maintaining the state of each sample. The initializer should set up internal data structures to store a "score" and a "weight" for every sample in the provided dataset. It also needs to store configuration parameters like the pruning ratio and the annealing schedule (`delta`), as detailed in Sections 2.3 and 2.4 of the InfoBatch paper.
42
- * **Expected Function Name:** `__init__` (as part of the `InfoBatch` class)
43
- * **Input:**
44
- * `dataset` (object): The original dataset object to be wrapped. It is expected to have a `__len__` method that returns the total number of samples.
45
- * `num_epochs` (int): The total number of epochs for training, used to determine the annealing schedule.
46
- * `prune_ratio` (float): The probability `r` of pruning a "well-learned" sample, as defined in Eq. 3 of the paper.
47
- * `delta` (float): The fraction of epochs during which pruning is active, corresponding to `δ` in Eq. 10 of the paper.
48
- * **Output:** An initialized `InfoBatch` object.
49
-
50
- ---
51
-
52
- #### **Instruction 4: Implement Attribute Delegation**
53
-
54
- * **Functionality Description:** Implement the `__getattr__` method to make the `InfoBatch` class a transparent wrapper. If a requested attribute or method is not found on the `InfoBatch` object itself, it should attempt to retrieve it from the underlying, original dataset.
55
- * **Expected Function Name:** `__getattr__` (as part of the `InfoBatch` class)
56
- * **Input:**
57
- * `name` (str): The name of the attribute being accessed.
58
- * **Output:**
59
- * `attribute` (object): The requested attribute from the wrapped dataset.
60
-
61
- ---
62
-
63
- #### **Instruction 5: Implement Active Indices Setter**
64
-
65
- * **Functionality Description:** Implement a method to store the indices of the samples that constitute the current batch being processed. This method will be called by the `info_hack_indices` monkey-patch.
66
- * **Expected Function Name:** `set_active_indices` (as part of the `InfoBatch` class)
67
- * **Input:**
68
- * `cur_batch_indices` (list of int): A list containing the integer indices of the samples in the current batch.
69
- * **Output:** None.
70
-
71
- ---
72
-
73
- #### **Instruction 6: Implement Score Update and Loss Rescaling**
74
-
75
- * **Functionality Description:** Implement the `update` method for the `InfoBatch` class. This function performs two critical tasks described in the paper: 1) It updates the scores of samples in the current batch with their new loss values (as per Eq. 4). 2) It applies expectation rescaling by multiplying the batch's loss values by their corresponding pre-calculated weights (as per Section 2.3), thereby scaling the gradients during backpropagation. The function must also be able to handle distributed scenarios by first gathering losses from all workers.
76
- * **Expected Function Name:** `update` (as part of the `InfoBatch` class)
77
- * **Input:**
78
- * `values` (list of float): A list of loss values, one for each sample in the current batch. The function will implicitly use the batch's sample indices that were set via `set_active_indices`.
79
- * **Output:**
80
- * `rescaled_loss_mean` (float): The mean of the rescaled loss values for the batch.
81
-
82
- ---
83
-
84
- #### **Instruction 7: Implement Dataset Length Method**
85
-
86
- * **Functionality Description:** Implement the `__len__` method to return the total number of samples in the original, unpruned dataset.
87
- * **Expected Function Name:** `__len__` (as part of the `InfoBatch` class)
88
- * **Input:** None.
89
- * **Output:**
90
- * `length` (int): The size of the dataset.
91
-
92
- ---
93
-
94
- #### **Instruction 8: Implement Indexed Item Retrieval**
95
-
96
- * **Functionality Description:** Implement the `__getitem__` method. To enable the data loader patch, this method must return not only the data sample from the original dataset but also its corresponding index.
97
- * **Expected Function Name:** `__getitem__` (as part of the `InfoBatch` class)
98
- * **Input:**
99
- * `index` (int): The index of the sample to retrieve.
100
- * **Output:**
101
- * `indexed_sample` (tuple): A tuple containing the `index` (int) and the `data_sample` (object).
102
-
103
- ---
104
-
105
- #### **Instruction 9: Implement Soft Pruning Logic**
106
-
107
- * **Functionality Description:** Implement the `prune` method for the `InfoBatch` class. This function executes the core soft pruning strategy for a single epoch. It first identifies "well-learned" samples by comparing their scores to the mean score of the entire dataset. It then randomly discards a fraction of these well-learned samples according to the `prune_ratio`. Finally, it updates the weights of the remaining well-learned samples to implement expectation rescaling, as described in Section 2.3 (Eq. 3 and surrounding text) of the paper.
108
- * **Expected Function Name:** `prune` (as part of the `InfoBatch` class)
109
- * **Input:** None (operates on the internal state of the `InfoBatch` object).
110
- * **Output:**
111
- * `remained_indices` (list of int): A shuffled list of the indices of all samples that should be used for training in the upcoming epoch.
112
-
113
- ---
114
-
115
- #### **Instruction 10: Implement Sampler Property**
116
-
117
- * **Functionality Description:** Implement a property that returns a correctly configured sampler instance for the `InfoBatch` dataset. It should create a standard `IBSampler` and, if in a distributed training environment, wrap it with the `DistributedIBSampler`.
118
- * **Expected Function Name:** `sampler` (as a property of the `InfoBatch` class)
119
- * **Input:** None.
120
- * **Output:**
121
- * `sampler` (object): An instance of `IBSampler` or `DistributedIBSampler`.
122
-
123
- ---
124
-
125
- #### **Instruction 11: Implement No-Prune Index Generation**
126
-
127
- * **Functionality Description:** Implement a method that generates a list of all sample indices from the dataset and shuffles them randomly. This is used during the annealing phase when pruning is disabled.
128
- * **Expected Function Name:** `no_prune` (as part of the `InfoBatch` class)
129
- * **Input:** None.
130
- * **Output:**
131
- * `shuffled_indices` (list of int): A randomly shuffled list of all indices from 0 to N-1, where N is the dataset size.
132
-
133
- ---
134
-
135
- #### **Instruction 12: Implement Mean Score Calculation**
136
-
137
- * **Functionality Description:** Implement a method to calculate and return the mean of all sample scores currently stored in the `InfoBatch` object.
138
- * **Expected Function Name:** `mean_score` (as part of the `InfoBatch` class)
139
- * **Input:** None.
140
- * **Output:**
141
- * `mean_score` (float): The average score across all samples.
142
-
143
- ---
144
-
145
- #### **Instruction 13: Implement Weight Retrieval**
146
-
147
- * **Functionality Description:** Implement a method to retrieve the rescaling weights for a given list of sample indices.
148
- * **Expected Function Name:** `get_weights` (as part of the `InfoBatch` class)
149
- * **Input:**
150
- * `indexes` (list of int): The indices of the samples for which to retrieve weights.
151
- * **Output:**
152
- * `weights` (list of float): The corresponding rescaling weights.
153
-
154
- ---
155
-
156
- #### **Instruction 14: Implement Pruned Count Retrieval**
157
-
158
- * **Functionality Description:** Implement a method to return the cumulative number of samples that have been pruned across all epochs so far.
159
- * **Expected Function Name:** `get_pruned_count` (as part of the `InfoBatch` class)
160
- * **Input:** None.
161
- * **Output:**
162
- * `count` (int): The total number of pruned samples.
163
-
164
- ---
165
-
166
- #### **Instruction 15: Implement Pruning Stop Condition**
167
-
168
- * **Functionality Description:** Implement a property that calculates the epoch number at which pruning should be stopped, based on the total number of epochs and the `delta` parameter, as described in Section 2.4 of the paper.
169
- * **Expected Function Name:** `stop_prune` (as a property of the `InfoBatch` class)
170
- * **Input:** None.
171
- * **Output:**
172
- * `epoch_number` (float): The epoch number that marks the end of the pruning phase.
173
-
174
- ---
175
-
176
- #### **Instruction 16: Implement Weight Reset**
177
-
178
- * **Functionality Description:** Implement a method to reset all sample weights to their default value of 1. This is typically used when transitioning into the annealing phase.
179
- * **Expected Function Name:** `reset_weights` (as part of the `InfoBatch` class)
180
- * **Input:** None.
181
- * **Output:** None.
182
-
183
- ---
184
-
185
- ### **`IBSampler` Class**
186
-
187
- ---
188
-
189
- #### **Instruction 17: Implement IBSampler Initialization**
190
-
191
- * **Functionality Description:** Implement the initializer for the `IBSampler`. This custom sampler orchestrates the epoch-by-epoch pruning and annealing schedule. The initializer should store a reference to the `InfoBatch` dataset, initialize an epoch counter, and call its own `reset` method to prepare the indices for the very first epoch.
192
- * **Expected Function Name:** `__init__` (as part of the `IBSampler` class)
193
- * **Input:**
194
- * `dataset` (object): An instance of the `InfoBatch` class.
195
- * **Output:** An initialized `IBSampler` object.
196
-
197
- ---
198
-
199
- #### **Instruction 18: Implement Sampler Indexed Get**
200
-
201
- * **Functionality Description:** Implement the `__getitem__` method to allow retrieving a sample index by its position in the current epoch's list of active indices.
202
- * **Expected Function Name:** `__getitem__` (as part of the `IBSampler` class)
203
- * **Input:**
204
- * `idx` (int): The position in the current epoch's index list.
205
- * **Output:**
206
- * `sample_index` (int): The actual sample index from the dataset.
207
-
208
- ---
209
-
210
- #### **Instruction 19: Implement Sampler State Reset**
211
-
212
- * **Functionality Description:** Implement the `reset` method for the `IBSampler` class. This function is called at the beginning of each epoch to generate the list of sample indices for the `DataLoader`. It must implement the annealing schedule described in Section 2.4 (Eq. 10) of the paper. Based on the current epoch number, it decides whether to call the `prune` method on its dataset to get a reduced set of indices or to use the full, shuffled dataset via `no_prune` (during the final annealing phase).
213
- * **Expected Function Name:** `reset` (as part of the `IBSampler` class)
214
- * **Input:** None (operates on the sampler's internal state, such as the current epoch count).
215
- * **Output:** None (it modifies the internal state by generating a new list of sample indices for the epoch).
216
-
217
- ---
218
-
219
- #### **Instruction 20: Implement Sampler Next Item**
220
-
221
- * **Functionality Description:** Implement the `__next__` method to make the sampler a valid iterator. It should return the next sample index from the internal list generated by the `reset` method for the current epoch.
222
- * **Expected Function Name:** `__next__` (as part of the `IBSampler` class)
223
- * **Input:** None.
224
- * **Output:**
225
- * `next_index` (int): The next sample index to be processed.
226
-
227
- ---
228
-
229
- #### **Instruction 21: Implement Sampler Length**
230
-
231
- * **Functionality Description:** Implement the `__len__` method to return the number of samples to be processed in the current epoch. This length can change from epoch to epoch depending on whether pruning is active.
232
- * **Expected Function Name:** `__len__` (as part of the `IBSampler` class)
233
- * **Input:** None.
234
- * **Output:**
235
- * `length` (int): The number of active sample indices for the current epoch.
236
-
237
- ---
238
-
239
- #### **Instruction 22: Implement Sampler Iterator**
240
-
241
- * **Functionality Description:** Implement the `__iter__` method. This should be called by the data loader at the start of each epoch. It must call the sampler's `reset` method to generate the new list of indices for the epoch and then return itself as the iterator.
242
- * **Expected Function Name:** `__iter__` (as part of the `IBSampler` class)
243
- * **Input:** None.
244
- * **Output:**
245
- * `iterator` (object): The sampler instance itself.
246
-
247
- ---
248
-
249
- ### **`DistributedIBSampler` Class**
250
-
251
- ---
252
-
253
- #### **Instruction 23: Implement Dataset-from-Sampler Wrapper (`DatasetFromSampler` nested class)**
254
-
255
- * **Functionality Description:** To make the dynamic `IBSampler` compatible with a standard distributed sampler, implement a simple wrapper class that makes the sampler look like a dataset. This involves implementing `__init__`, `__len__`, `__getitem__`, and a `reset` method that delegates the call to the wrapped sampler.
256
- * **Expected Function Names:** `__init__`, `reset`, `__len__`, `__getitem__` (as part of the `DatasetFromSampler` nested class)
257
- * **Input (`__init__`):**
258
- * `sampler` (object): An instance of `IBSampler`.
259
- * **Output (`__init__`):** An initialized `DatasetFromSampler` object.
260
-
261
- ---
262
-
263
- #### **Instruction 24: Implement Distributed Sampler Initialization**
264
-
265
- * **Functionality Description:** Implement the initializer for the `DistributedIBSampler`. This class wraps the `IBSampler` to make it work in a multi-process distributed training setting. The initializer should accept the base sampler and standard distributed training parameters (`num_replicas`, `rank`, etc.) and set up the necessary internal state. It should use the `DatasetFromSampler` wrapper internally to integrate with the parent `DistributedSampler`'s logic.
266
- * **Expected Function Name:** `__init__` (as part of the `DistributedIBSampler` class)
267
- * **Input:**
268
- * `dataset` (object): An instance of the `IBSampler` to be wrapped.
269
- * `num_replicas` (int, optional): The number of processes participating in distributed training.
270
- * `rank` (int, optional): The rank of the current process.
271
- * `shuffle` (bool): If `True`, shuffle the indices each epoch.
272
- * `seed` (int): A random seed for shuffling.
273
- * `drop_last` (bool): If `True`, drop the last non-full batch.
274
- * **Output:** An initialized `DistributedIBSampler` object.
275
-
276
- ---
277
-
278
- #### **Instruction 25: Implement Distributed Sampler Iterator**
279
-
280
- * **Functionality Description:** Implement the iterator-generating method (`__iter__`) for the `DistributedIBSampler`. This function must ensure that when training across multiple processes, each process receives a unique, non-overlapping subset of the sample indices for the current epoch. It should first trigger the `reset` on the underlying `IBSampler` to generate the complete list of indices for the epoch. Then, it should shuffle (if enabled) and partition this list, distributing a unique slice to each process. The logic must also handle cases where the data is not perfectly divisible by the number of processes, either by dropping the last few samples or by padding the list with duplicates.
281
- * **Expected Function Name:** `__iter__` (as part of the `DistributedIBSampler` class)
282
- * **Input:** None (operates on internal state, including rank, world size, and the base sampler).
283
- * **Output:**
284
- * `iterator` (iterator of int): An iterator that yields the sample indices assigned to the current process for one epoch.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/latex.txt DELETED
@@ -1,85 +0,0 @@
1
- \section{How We Can Achieve Lossless Result}
2
-
3
- \subsection{Preliminaries}
4
-
5
- \textbf{Static Pruning.} Given a dataset $\mathcal{D} = \{z_i\}|_{i=1}^{|\mathcal{D}|} = \{(x_i, y_i)\}|_{i=1}^{|\mathcal{D}|}$, a score $\mathcal{H}(z)$ can be defined for each sample. For the pruning process, samples are discarded by a pruning probability $\mathcal{P}$ defined on top of $\mathcal{H}$. Static pruning directly discards all samples satisfying a certain condition before training, resulting in $\mathcal{P}(z;\mathcal{H})\in\{0,1\}$. For examples, \cite{toneva2018empirical} defines:
6
- \begin{equation}
7
- \mathcal{P}(z;\mathcal{H})=\mathds{1}(\mathcal{H}(z)<\bar{\mathcal{H}}),
8
- \end{equation}
9
- where $\bar{\mathcal{H}}$ is a threshold and $\mathds{1}(\cdot)$ is indicator function. A subset $\mathcal{S}$ is formed by pruning samples with $\mathcal{P}(z;\mathcal{H})=1$.
10
- Fig.~\ref{fig:1a} briefly illustrates the whole process of static pruning. A more detailed theoretical analysis is provided in Appendix~\ref{ap_sec:theoretical}.
11
-
12
- \textbf{Dynamic Pruning.} For dynamic pruning, pruning is done across training, and the score $\mathcal{H}_t$ can change along training steps, where $t$ denotes the temporal status. The probability is step-dependent:
13
- \begin{equation}
14
- \mathcal{P}_t(z) = \mathcal{P}(z;\mathcal{H}_t), \label{eq:dyna}
15
- \end{equation}
16
- and forms a dynamically pruned dataset $\mathcal{S}_{t}$. Compared to static pruning, dynamic pruning has access to all the original data during training. Thus the gradient expectation bias should be much smaller than static pruning.
17
- However, such a scheme still has the following limitations: i). As claimed in~\cite{raju2021ddp}, low-score samples of different $t$ during the training could easily overlap. Directly pruning them every time may still lead to a bias (see in Fig.~\ref{fig:1a}). ii). Pruning samples leads to reduced number of gradient updates. Under the premise of saving training cost, existing dynamic pruning methods~\cite{raju2021ddp} hardly achieve lossless results compared to training on the original dataset.
18
- iii). Scoring and sorting operations in dynamic pruning are conducted repeatedly, the overhead of which is still non-negligible on large-scale datasets.
19
-
20
- \begin{figure*}[h]
21
- \centering
22
- \includegraphics[width=\linewidth]{figures/pipeline.pdf}
23
- \caption{Illustration of the proposed \textit{InfoBatch} framework. InfoBatch mainly consists of two operations, named soft pruning and expectation rescaling. $\bar{\mathcal{H}}_{t}$ denotes the adaptive thresholds of scores of samples. Soft pruning randomly prunes some samples from $\mathcal{D}_1$ with relatively small scores. For remaining samples from $\mathcal{D}_1$, expectation rescaling scales up the losses to keep the approximately same gradient expectation as the original dataset.}
24
- \label{fig:pipeline}
25
- \vspace{-10pt}
26
- \end{figure*}
27
-
28
- \subsection{Overview of InfoBatch}
29
- Based on the above observation and analysis, we propose InfoBatch, a novel framework for achieving lossless training acceleration based on unbiased dynamic data pruning.
30
- As illustrated in Fig.~\ref{fig:pipeline}, a score is maintained for each sample with its loss value during forward propagation. The mean of these values are set as the pruning threshold.
31
- A certain portion of small-score samples is accordingly pruned in each epoch.
32
- Then, to obtain the same expectation of gradient as the original dataset in each epoch, the gradients of the remaining small-score samples are scaled up.
33
- By doing this, compared to previous static and dynamic pruning methods,
34
- InfoBatch mitigates the performance differences between training on the pruned dataset and the original dataset.
35
- In order to further reduce the performance variance, we train with the full dataset in the last few epochs.
36
-
37
- \subsection{Unbiased Prune and Rescale}
38
- \label{theoritical_analysis}
39
-
40
- InfoBatch adopts the dynamic pruning process as in Eqn.~\ref{eq:dyna}.
41
- We first define its pruning policy $\mathcal{P}_t$.
42
- Previous methods using a deterministic pruning operation could cause bias as discussed above. In contrast, InfoBatch introduces randomness into the pruning process to solve this.
43
- Given a dataset $\mathcal{D}$, in $t$-th epoch, a pruning probability is assigned to each sample based on its score. Such a soft pruning policy is formulated as:
44
- \begin{equation}
45
- \mathcal{P}_{t}(z)= \begin{cases}
46
- r,\quad &\mathcal{H}_{t}(z) < \bar{\mathcal{H}_{t}} \\
47
- 0,\quad &\mathcal{H}_{t}(z) \geq \bar{\mathcal{H}_{t}}
48
- \end{cases},
49
- \end{equation}
50
- where $\bar{\mathcal{H}_{t}}$ is the mean value of all the scores $\mathcal{H}_{t}$ and $r \in (0,1)$ is a predefined hyper-parameter as the pruning probability. This new prune policy has the following benefits: i). Soft pruning allows each small-score sample to be utilized for training, which reduces the bias caused by hard pruning in previous dynamic pruning methods.
51
- ii). The proposed strategy is based on the comparison with $\bar{\mathcal{H}_{t}}$, with no requirement to sort the whole training samples, which reduces the time complexity from $O(logN)$ to $O(1)$. It indicates that InfoBatch could be more efficient on large-scale datasets.
52
-
53
- Then, we utilize loss values $\mathcal{L}(z)$ of each sample as the corresponding score based on the following two reasons: i). loss values can be obtained without extra cost, ii). loss values reflect the learning status of samples~\citep{cilimkovic2015neural}. Specifically, before the $t$-th ($t>0$) epoch, we utilize the soft pruning policy to prune samples based on their scores.
54
- Then for the pruned samples, their scores remain unmodified as previous. For the remaining samples, their scores are updated by the losses in the current epoch. Mathematically, $\mathcal{H}_{t}(z)$ would be updated by the latest losses to $\mathcal{H}_{t+1}(z)$ by:
55
- \begin{equation}
56
- \mathcal{H}_{t+1}(z)= \begin{cases}
57
- \mathcal{H}_{t}(z),\quad & z \in \mathcal{D}\backslash \mathcal{S}_{t} \\
58
- \mathcal{L}(z),\quad & z \in \mathcal{S}_{t}
59
- \end{cases}.
60
- \end{equation}
61
- Note that, for the first epoch, we initialize the scores with $\{1\}$ provided no previous loss.
62
-
63
- There are several benefits of the soft pruning policy, yet it still cannot avoid the influence caused by the reduced number of gradient updates. To address this issue, we scale up the gradients of the remaining samples. Specifically, given a remaining sample with score $\mathcal{H}(z)<\bar{\mathcal{H}}_{t}$, whose corresponding pruning probability is $r$, its gradient is scaled to $1/(1-r)$ times of original.
64
- For the samples with scores no less than $\bar{\mathcal{H}}_{t}$, the loss is not modified.
65
- Thereby the gradient update expectation is approximately equal to training on the original dataset.
66
- Besides, as the rescaling is operated on small-score samples, it further refines the direction of gradient update expectation.
67
- We provide the following theoretical analysis to demonstrate the necessity and advantages of expectation rescaling.
68
-
69
- \subsection{Annealing}
70
- Based on the theoretical analysis above, the objectives and updating expectations between InfoBatch and training on the original dataset are approximately the same. However, there still exist minor differences between the optimization on $\mathcal{D}$ and $\mathcal{S}_{t}$.
71
- During training, if a sample is pruned in the middle stage, it is still likely to be revisited afterward.
72
- However, in the last few epochs, the revisiting probability drastically drops, resulting in remaining gradient expectation bias.
73
- Therefore, given training epoch $C$, we define a ratio hyper-parameter $\delta\in(0,1)$.
74
- The pruning is only conducted in the first $\delta\cdot C$ epochs (in practice, $\delta$ is close to 1 so InfoBatch saves at a reasonable ratio).
75
- After that, we train on the full dataset till the end.
76
- The corresponding operation can be interpreted as
77
- \begin{equation}
78
- \mathcal{P}_{t}(z)= \begin{cases}
79
- r,\quad &\mathcal{H}_{t}(z) < \bar{\mathcal{H}_{t}}
80
- \land t < \delta\cdot C \\
81
- 0,\quad &\mathcal{H}_{t}(z) \geq \bar{\mathcal{H}}_{t}
82
- \lor t \geq \delta\cdot C
83
- \end{cases}.
84
- \end{equation}
85
- Combining the above components, InfoBatch achieves lossless training performance with fewer iterations compared with training on the original dataset.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/pytest_report/report.xml DELETED
@@ -1 +0,0 @@
1
- <?xml version="1.0" encoding="utf-8"?><testsuites name="pytest tests"><testsuite name="pytest" errors="0" failures="0" skipped="0" tests="6" time="2.256" timestamp="2025-08-31T13:40:10.828588-05:00" hostname="linus-ms7e59"><testcase classname="infobatch.test.TestInfoBatchImplementation" name="test_dataloader_integration_and_patch" time="1.273" /><testcase classname="infobatch.test.TestInfoBatchImplementation" name="test_infobatch_init" time="0.002" /><testcase classname="infobatch.test.TestInfoBatchImplementation" name="test_infobatch_len_and_getitem" time="0.000" /><testcase classname="infobatch.test.TestInfoBatchImplementation" name="test_prune_and_no_prune" time="0.003" /><testcase classname="infobatch.test.TestInfoBatchImplementation" name="test_sampler_logic" time="0.006" /><testcase classname="infobatch.test.TestInfoBatchImplementation" name="test_update_method" time="0.001" /></testsuite></testsuites>
 
 
annotations/annotation_127/requirements.txt DELETED
@@ -1,30 +0,0 @@
1
- filelock==3.13.1
2
- fsspec==2024.6.1
3
- Jinja2==3.1.4
4
- MarkupSafe==2.1.5
5
- mpmath==1.3.0
6
- networkx==3.3
7
- numpy==2.1.2
8
- nvidia-cublas-cu12==12.9.1.4
9
- nvidia-cuda-cupti-cu12==12.9.79
10
- nvidia-cuda-nvrtc-cu12==12.9.86
11
- nvidia-cuda-runtime-cu12==12.9.79
12
- nvidia-cudnn-cu12==9.10.2.21
13
- nvidia-cufft-cu12==11.4.1.4
14
- nvidia-cufile-cu12==1.14.1.1
15
- nvidia-curand-cu12==10.3.10.19
16
- nvidia-cusolver-cu12==11.7.5.82
17
- nvidia-cusparse-cu12==12.5.10.65
18
- nvidia-cusparselt-cu12==0.7.1
19
- nvidia-nccl-cu12==2.27.3
20
- nvidia-nvjitlink-cu12==12.9.86
21
- nvidia-nvtx-cu12==12.9.79
22
- pillow==11.0.0
23
- pip==25.1
24
- setuptools==78.1.1
25
- sympy==1.13.3
26
- torch==2.8.0+cu129
27
- torchvision==0.23.0+cu129
28
- triton==3.4.0
29
- typing_extensions==4.12.2
30
- wheel==0.45.1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/test.py DELETED
@@ -1,161 +0,0 @@
1
- import unittest
2
- import torch
3
- import numpy as np
4
- import os
5
- import random
6
- from torch.utils.data import TensorDataset, DataLoader
7
-
8
- # Assume the canonical code is in a file named `canonical.py`
9
- # and the generated code is in a file named `generated.py`.
10
- from .canonical import InfoBatch as CanonicalInfoBatch, IBSampler as CanonicalIBSampler
11
- from .infobatch import InfoBatch as GeneratedInfoBatch, IBSampler as GeneratedIBSampler
12
-
13
- from torch.utils.data.dataloader import _BaseDataLoaderIter
14
- from .canonical import info_hack_indices as canonical_patch
15
- from .infobatch import info_hack_indices as generated_patch
16
-
17
-
18
- def set_seed(seed=42):
19
- """Sets the seed for reproducibility."""
20
- random.seed(seed)
21
- os.environ['PYTHONHASHSEED'] = str(seed)
22
- np.random.seed(seed)
23
- torch.manual_seed(seed)
24
- if torch.cuda.is_available():
25
- torch.cuda.manual_seed(seed)
26
- torch.cuda.manual_seed_all(seed)
27
- torch.backends.cudnn.deterministic = True
28
- torch.backends.cudnn.benchmark = False
29
-
30
- class TestInfoBatchImplementation(unittest.TestCase):
31
-
32
- def setUp(self):
33
- """Set up common variables and data for tests."""
34
- set_seed(42)
35
- self.dataset_size = 20
36
- self.num_epochs = 10
37
- self.prune_ratio = 0.5
38
- self.delta = 0.8 # Pruning will stop AT epoch 8 (10 * 0.8)
39
-
40
- features = torch.randn(self.dataset_size, 5)
41
- labels = torch.randint(0, 2, (self.dataset_size,))
42
- self.base_dataset = TensorDataset(features, labels)
43
-
44
- self.canonical_infobatch = CanonicalInfoBatch(
45
- self.base_dataset, self.num_epochs, self.prune_ratio, self.delta
46
- )
47
- self.generated_infobatch = GeneratedInfoBatch(
48
- self.base_dataset, self.num_epochs, self.prune_ratio, self.delta
49
- )
50
-
51
- self.original_next = _BaseDataLoaderIter.__next__
52
-
53
- def tearDown(self):
54
- """Restore the original DataLoader iterator method after tests."""
55
- _BaseDataLoaderIter.__next__ = self.original_next
56
-
57
- def test_infobatch_init(self):
58
- """Tests the initialization of the InfoBatch class."""
59
- self.assertEqual(self.canonical_infobatch.num_epochs, self.generated_infobatch.num_epochs)
60
- self.assertAlmostEqual(self.canonical_infobatch.keep_ratio, self.generated_infobatch.keep_ratio)
61
- self.assertEqual(self.canonical_infobatch.delta, self.generated_infobatch.delta)
62
- torch.testing.assert_close(self.canonical_infobatch.scores, self.generated_infobatch.scores)
63
-
64
- def test_infobatch_len_and_getitem(self):
65
- """Tests the __len__ and __getitem__ methods."""
66
- self.assertEqual(len(self.canonical_infobatch), len(self.generated_infobatch))
67
- index = 5
68
- canonical_idx, _ = self.canonical_infobatch[index]
69
- generated_idx, _ = self.generated_infobatch[index]
70
- self.assertEqual(canonical_idx, generated_idx)
71
-
72
- def test_prune_and_no_prune(self):
73
- """Tests the core pruning and no-pruning logic."""
74
- scores = torch.linspace(0.1, 2.0, self.dataset_size)
75
- self.canonical_infobatch.scores = scores.clone()
76
- self.generated_infobatch.scores = scores.clone()
77
-
78
- set_seed(123)
79
- canonical_pruned_indices = self.canonical_infobatch.prune()
80
- set_seed(123)
81
- generated_pruned_indices = self.generated_infobatch.prune()
82
- self.assertEqual(sorted(canonical_pruned_indices), sorted(generated_pruned_indices))
83
-
84
- def test_update_method(self):
85
- """Tests the score update and loss rescaling logic."""
86
- batch_indices = torch.tensor([2, 5, 10, 15])
87
- loss_values = torch.rand(len(batch_indices))
88
-
89
- self.canonical_infobatch.set_active_indices(batch_indices.clone())
90
- self.generated_infobatch.set_active_indices(batch_indices.clone())
91
-
92
- canonical_rescaled_loss = self.canonical_infobatch.update(loss_values.clone())
93
- generated_rescaled_loss = self.generated_infobatch.update(loss_values.clone())
94
-
95
- torch.testing.assert_close(canonical_rescaled_loss, generated_rescaled_loss)
96
- torch.testing.assert_close(self.canonical_infobatch.scores, self.generated_infobatch.scores)
97
-
98
- def test_sampler_logic(self):
99
- """Tests the IBSampler's epoch-based pruning and annealing schedule."""
100
- # Use highly distinct scores to make the test more robust and avoid float precision issues.
101
- # Here, the first 10 samples are clearly "well-learned" and the last 10 are not.
102
- varied_scores = torch.tensor([0.1] * 10 + [5.0] * 10, dtype=torch.float32)
103
- self.canonical_infobatch.scores = varied_scores.clone()
104
- self.generated_infobatch.scores = varied_scores.clone()
105
-
106
- canonical_sampler = CanonicalIBSampler(self.canonical_infobatch)
107
- generated_sampler = GeneratedIBSampler(self.generated_infobatch)
108
-
109
- # The sampler's __init__ calls reset() once. We reset the counter to 0
110
- # to have a clean start for our test loop.
111
- canonical_sampler.iterations = 0
112
- generated_sampler.iterations = 0
113
-
114
- for epoch in range(self.num_epochs):
115
- # The sampler's __iter__ method calls reset(), which uses the *current* value of
116
- # `sampler.iterations` to decide whether to prune and to seed the RNG.
117
- # Then, it increments the counter for the *next* epoch.
118
- current_sampler_internal_iteration = canonical_sampler.iterations
119
-
120
- set_seed(epoch) # Seed for the generated sampler to ensure its RNG state matches
121
- generated_indices = list(iter(generated_sampler))
122
-
123
- set_seed(epoch) # Re-seed for the canonical sampler
124
- canonical_indices = list(iter(canonical_sampler))
125
-
126
- self.assertEqual(len(canonical_indices), len(generated_indices), f"Epoch {epoch}: Sampler lengths do not match.")
127
- self.assertEqual(sorted(canonical_indices), sorted(generated_indices), f"Epoch {epoch}: Sampled indices do not match.")
128
-
129
- # **THE FIX**: The sampler's logic is `if self.iterations > self.stop_prune:`.
130
- # Since `iterations` is checked *before* it's incremented, the correct check is against the epoch number.
131
- # Pruning occurs for epochs 0, 1, 2, 3, 4, 5, 6, 7.
132
- # Annealing (no pruning) begins when the epoch number (which is the same as the sampler's internal iteration count
133
- # at the time of the check) is 8 or greater.
134
- if current_sampler_internal_iteration >= canonical_sampler.stop_prune:
135
- self.assertEqual(len(canonical_indices), self.dataset_size, f"Epoch {epoch}: Annealing phase failed. Expected full dataset.")
136
- else:
137
- self.assertLess(len(canonical_indices), self.dataset_size, f"Epoch {epoch}: Pruning phase failed. Expected a pruned dataset.")
138
-
139
- def test_dataloader_integration_and_patch(self):
140
- """Tests if the monkey-patch correctly sets the active indices on the InfoBatch dataset."""
141
- _BaseDataLoaderIter.__next__ = canonical_patch
142
- canonical_loader = DataLoader(self.canonical_infobatch, batch_size=4, shuffle=False)
143
-
144
- # The loader iterator will call the patch, which finds the indices and sets them.
145
- next(iter(canonical_loader))
146
-
147
- self.assertIsNotNone(self.canonical_infobatch.cur_batch_index)
148
- expected_indices = torch.tensor([0, 1, 2, 3])
149
- torch.testing.assert_close(self.canonical_infobatch.cur_batch_index, expected_indices)
150
-
151
- _BaseDataLoaderIter.__next__ = generated_patch
152
- generated_loader = DataLoader(self.generated_infobatch, batch_size=4, shuffle=False)
153
-
154
- next(iter(generated_loader))
155
-
156
- self.assertIsNotNone(self.generated_infobatch.cur_batch_index)
157
- torch.testing.assert_close(self.generated_infobatch.cur_batch_index, expected_indices)
158
-
159
-
160
- if __name__ == '__main__':
161
- unittest.main(argv=['first-arg-is-ignored'], exit=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_127/test.sh DELETED
@@ -1,23 +0,0 @@
1
- #!/bin/bash
2
- eval "$(conda shell.bash hook)"
3
- conda activate test_common1
4
-
5
- # Absolute path to the script location
6
- SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
7
-
8
- # Define the target directory relative to this script
9
- TARGET_DIR="${SCRIPT_DIR}/InfoBatch"
10
-
11
- # Copy files to target directory
12
- cp "${SCRIPT_DIR}/canonical.py" "${TARGET_DIR}/infobatch/."
13
- cp "${SCRIPT_DIR}/test.py" "${TARGET_DIR}/infobatch/."
14
-
15
- # Run pytest from inside the target directory
16
- # Change to target directory
17
- cd "${TARGET_DIR}/infobatch" || exit 1
18
- PYTHONPATH="${TARGET_DIR}/infobatch" pytest --timeout=10 test.py \
19
- --junitxml="${SCRIPT_DIR}/pytest_report/report.xml"
20
-
21
-
22
- # Clean up copied files
23
- rm -f "${TARGET_DIR}/infobatch/canonical.py" "${TARGET_DIR}/infobatch/test.py"